我有一个看起来像这样的C文件: #include stdio.h #include sys/types.h #include unistd.h int main () { pid_t child_pid; printf ("The PID is %d\n", (int) getpid ()); child_pid = fork (); if (child_pid != 0) { printf ("this is the
#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main () { pid_t child_pid; printf ("The PID is %d\n", (int) getpid ()); child_pid = fork (); if (child_pid != 0) { printf ("this is the parent process, with PID %d\n", (int)getpid()); printf ("the child's PID is %d\n", (int) child_pid); } else printf ("this is the child process, with PID %d\n", (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 }