使用fork()的创建子进程,我想作一棵树,看起来像这样:使用fork()创建只有2孙子三个子进程
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
你*确实知道'''是短路吗? – EOF
是否需要通过单个表达式执行所有分叉? –
供您参考:https://en.wikipedia.org/wiki/Short-circuit_evaluation – alk