我正在创建一个包含n个进程的2级树,父进程创建了n个孩子,每个孩子都创建了n个孩子,所以树看起来像这样
n = 3
P
/ | \
P P P
/|\ /|\ / | \
P P P P P P P P P
我放了2个waitpid,一个这样的1级进程等待所有2级进程完成,而一个父进程等待所有子进程完成
pid_t child_pid[1000], grandchild_pid[1000];
for (int progress=0; progress<children; progress++) {
child_pid[progress] = fork();
if (child_pid[progress]<0){
perror("fork");
exit(-1);
}
else if (child_pid[progress]>0){
//do something, parent
}
else if (child_pid[progress] == 0) {
printf("child pid %d parent pid %d\n",getpid(),getppid());fflush(stdout);
for (int g = 0; g<children; g++){
grandchild_pid[g] = fork();
if (grandchild_pid[g]<0){
perror("fork");
exit(-1);
}
else if (grandchild_pid[g] == 0) {
printf("grandchild pid %d parent pid %d\n",getpid(),getppid());fflush(stdout);
//do something with the grandchild
exit(0);
}
}
for (int progress = 0; progress<children; progress++){
waitpid(grandchild_pid[progress],&status,WUNTRACED);
}
printf("All grandchildren from process %d finished\n",progress);
exit(0);
}
for (int progress = 0; progress<children; progress++){
waitpid(child_pid[progress],&status,WUNTRACED);
}
它应该执行以下操作: n = 3
child pid 3697 parent pid 3694
child pid 3696 parent pid 3694
child pid 3695 parent pid 3694
grandchild pid 3703 parent pid 3696
grandchild pid 3702 parent pid 3696
grandchild pid 3701 parent pid 3696
All grandchildren from process 0 finished
grandchild pid 3698 parent pid 3697
grandchild pid 3700 parent pid 3697
grandchild pid 3699 parent pid 3697
All grandchildren from process 1 finished
grandchild pid 3704 parent pid 3695
grandchild pid 3705 parent pid 3695
grandchild pid 3706 parent pid 3695
All grandchildren from process 2 finished
但是它正在这样做
child pid 3697 parent pid 3694
child pid 3696 parent pid 3694
child pid 3695 parent pid 3694
grandchild pid 3703 parent pid 3696
grandchild pid 3700 parent pid 3697
grandchild pid 3699 parent pid 3697
grandchild pid 3702 parent pid 3696
grandchild pid 3701 parent pid 3696
All grandchildren from process 0 finished
grandchild pid 3698 parent pid 3697
grandchild pid 3704 parent pid 3695
All grandchildren from process 1 finished
grandchild pid 3705 parent pid 3695
grandchild pid 3706 parent pid 3695
All grandchildren from process 2 finished
该如何解决?