Thursday, October 31, 2013

wait() and fork() Function

Wait function is used to wait for state changes in a child process of the calling process, and obtain information about the child whose state has been changed. A state change can be termination of a child or termination by a signal or resume of child by a signal. If a child has already changed the state these return immediately.

Header file:<sys/types.h>,<sys/wait.h>

While going through http://programmingundersecurity.blogspot.in/2013/10/understanding-fork-in-c.html you must have come across a point that for controlling the execution order(that is 'parent'->'child'->'parent resumes') we must wait until the child process has completed execution. So in order to work with that we use wait() function. wait() takes the address of an int and puts the exit status of the child it waited for.
Consider the code:

 #include <stdio.h>   
 #include <unistd.h>   
 #include <stdlib.h>  
 int main ()   
 {   
  int pid,status;   
  printf("Hello World\n");   
  pid = fork();   
 wait(&status);  
  if(pid==-1)  
     printf("\nError unable call fork");  
  else if(pid != 0)   
   printf("I'm the Father,my son's PID is %d and exit status is %d\n",pid,status);   
  else   
   { printf("I'm the Son\n");   
     exit(0);}  
  printf("Goodbye Cruel World\n");   
 }  


Output

 Hello World  
 I'm the Son  
 I'm the Father,my son's PID is 2750 and exit status is 0  
 Goodbye Cruel World  

This was the oupt without using wait:
  Hello World   
  I'm the Father and my son's PID is 2749   
  Goodbye Cruel World   
  I'm the Son   
  Goodbye Cruel World   
Clearly the execution order has changed and the parent waited for the child to finish execution.
tags:wait, fork, execution, process, programming, c

No comments:

Post a Comment