控制C中的前叉
发布时间:2020-12-16 09:24:31 所属栏目:百科 来源:网络整理
导读:我有一个看起来像这样的C文件: #include stdio.h #include sys/types.h #include unistd.h int main () { pid_t child_pid; printf ("The PID is %dn",(int) getpid ()); child_pid = fork (); if (child_pid != 0) { printf ("this is the parent process
我有一个看起来像这样的C文件:
#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main () { pid_t child_pid; printf ("The PID is %dn",(int) getpid ()); child_pid = fork (); if (child_pid != 0) { printf ("this is the parent process,with PID %dn",(int)getpid()); printf ("the child's PID is %dn",(int) child_pid); } else printf ("this is the child process,(int)getpid()); return 0; } 我需要修改它以产生一个看起来像的层次结构 parent (0) | +---> child (1) | +---> child (2) | +----> child (3) | +----> child (4) | +----> child (5) | 基本上是一个树形结构,每个第二个孩子生两个新孩子.据我所知,当我fork()一个进程时,每个进程将同时运行.在if语句中添加fork()似乎正常工作并正确创建进程0到2,因为只有父进程才会创建新的fork.但我不知道如何制作进程2 fork而不是1.任何想法? 解决方法
那么,第一个fork将创建进程1.进程2将由if语句中的fork创建.因此,为了让进程2 fork也是如此,如果第二个fork没有返回0,则在if语句中再次进行fork.
举例说明: if(fork) { // Inside process 0 if(fork) { // still in process 0 } else { // in process 2 if(fork) { // still in process 2 } else { // in prcess 3 } // and so on } } else { // Inside process 1 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |