【发布时间】:2024-01-14 13:40:01
【问题描述】:
使用 fork() 创建子进程,我正在尝试制作一个如下所示的树:
p
/ | \
p p p
/ \
p p
我让父进程创建了三个子进程,但我无法让两个外部子进程停止分叉,而第二个子进程只分叉两次。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t lchildpid, rchildpid,mchildpid, parentpid;
int n = 0;
lchildpid = 0;
rchildpid = 0;
mchildpid = 0;
printf("\nLvl\tProc\tParent\tChild 1\tChild 2\tChild 3\n");
printf("No.\tID\tID\tID\tID\tID\n");
while(n < 3){
if((lchildpid = fork()) == 0 || (mchildpid = fork()) == 0 || (rchildpid = fork()) == 0) {
parentpid = getppid();
n++;
continue;
}
//check for forking errors
if(lchildpid == -1 || rchildpid == -1 || mchildpid == -1)
{
perror("\n The fork failed\n");
exit(1);
}
//If current fork has two children, print complete generation to console and exit while loop
if(lchildpid && rchildpid && mchildpid ){
printf("%d\t%ld\t%ld\t%ld\t%ld\t%ld\n",n, (long)getpid(), (long)getppid(), (long)lchildpid, (long)mchildpid,(long)rchildpid);
break;
}
}
exit(0);
}
这是我的输出:
Lvl Proc Parent Child 1 Child 2 Child 3
No. ID ID ID ID ID
0 22 7 23 24 25
1 23 1 26 28 32
1 25 1 29 31 33
1 24 1 27 30 34
我想要这个输出:
Lvl Proc Parent Child 1 Child 2 Child 3
No. ID ID ID ID ID
0 40 7 41 42 43
1 41 40 0 0 0
1 42 40 44 45 0
1 43 40 0 0 0
【问题讨论】:
-
你确实知道
||正在短路吗? -
是否需要通过一个表达式执行所有的分叉?
-
不,不需要。