Reputation: 51
a c program that forks 2 child,first one sleeps for 10 sec,the second one waits for the exit of the first child and prints a related message,the parent waits for the termination of the 2 child,i do not know why the second child does not wait for the 1st child termination.plz help
#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;
}
Upvotes: 0
Views: 7175
Reputation: 2161
In process hierarchy children doesn't wait neither for parent nor for another children. You can use some form of IPC mechanism to communicate the info from 1 child to another,
Upvotes: 0
Reputation: 500167
The wait
family of functions can only be used by parent to wait for a child. They can't be used by a process to wait for a sibling.
Upvotes: 4
Reputation: 140445
A process can only wait
for its immediate children. In this case, that means the parent process has to do the wait
for both child1 and child2.
Upvotes: 3