Process Synchronization
main(){
int i=0; pid;
pid=fork();
if(0 == pid){
printf(“Child Starts\n”);
for(i=0;i<1000;i++){
printf(“%d \t”, i);
}
printf(“Child Ends \n”);
}
else{
wait(0);
printf(“Parent\n”);
}
}
The call to the wait() function results in the following things:
1. A check is made to see if the parent process has any children. If it does not, a -1 is returned by wait().
2. If the parent process has a child that has terminated, its PID is returned to the parent process & the child process is removed from the PROCESS TABLE.
3. If the parent process has any children that have not yet terminated (a Zombie), the parent process is suspended till it receives a signal. The signal is received as soon as the child dies.
Thus in the above code, the parent process is suspended till the child process is terminated. After this, a signal is sent to the parent process which before resuming, checks for any zombie children in the process table & removes it.
To wait for all children to terminate, a wait(0) for each child should be added in the parents code.
