分叉 2 个孩子的 ac 程序,第一个休眠 10 秒,第二个等待第一个孩子退出并打印相关消息,父母等待 2 个孩子的终止,我不知道为什么第二个孩子不等待第一个孩子终止。请帮助
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
main(){
int status;
pid_t child1, child2,ret,ret2;
child1=fork();
if(child1==0){
//this branch of code is being executed by the child1 process
printf("I'm the first child with %d, I sleep for 10 sec \n",getpid());
sleep(10);
printf("child1 pid %d exiting\n",getpid());
exit(1);
}
if(child1>0){
child2=fork();
ret=waitpid(child1,&status,0);
if(child2==0){
wait(&status);//???why child2 does not wait the child1 exit?
printf("I'm the second child with %d, I have waited for the termination of the first child\n",getpid());
printf("child2 exited\n");
exit(1);
}
if(child2>0){
printf("father of child2 is waiting\n");
ret2=waitpid(child2,&status,0);
printf("I'm the father, my terminated process id is: %d \n",getpid());
printf("I'm the father, my first child's id is: %d\n", child1);
printf("I'm tha father, my second child's id is: %d\n", child2);
}
}
return 0;
}