我正在尝试构建这样的进程树:
P1
/ \
P3 P2
\
P4
\
....
但是我无法使其正常工作。我尝试了此操作,但它只与P1一起使用。
for(int i = 0; i < depth; i++) {
int _pid = fork();
if(_pid == 0) {
printf("[son] pid %d from [parent] pid %d\n", getpid(), getppid());
exit(0);
}
}
wait(NULL);
仅使用一个fork
调用的要求使解决方案既繁琐又丑陋,但仍然可以像这样进行:
[步骤1:创建一个内部循环,如果i
为0,则将运行两次,对于任何i > 0
,将运行一次。
步骤2:仅在外循环的第一次迭代之后才在子进程中分叉。
步骤3:退出在内部循环的第二次迭代中分叉的子代。
int cur_pid = 0;
printf("Root PID %d started by %d\n", getpid(), getppid());
for (int i = 0; i < depth && cur_pid == 0; i++) {
for (int j = 0; j < (i ? 1 : 2); j++) {
cur_pid = fork();
if (cur_pid == 0) {
printf("[son] pid %d from [parent] pid %d\n", getpid(), getppid());
if (j == 1) {
exit(0);
} else {
break;
}
} else if (cur_pid < 0) {
printf("Error forking at PID %d\n", getpid());
}
}
}
wait(NULL);
如果您想让wait
返回有效值,请记住每个迭代的子进程的getppid
!