Waiting For a Process
=====================
- Sometime we would like to find out when a child process has finished.
- It is needed for parent process to wait until the child finishes before continuing by calling wait.
- It has prototype :
pid_t wait(int *stat_loc);
- It is declared in header :
#include<sys/wait.h>
- It has a return type pid_t which is declared in header :
#include<sys/types.h>
- The wait system call causes a parent process to pause until one of its child processes is stopped.
- The wait returns PID of child process which is terminated.
- The status information determine the exit status of child process (i.e value returned from main or passed to exit)
- If stat_loc is not a null pointer, the status information will be written to location to which it points.
- The status information can be determined by using macros defined in header sys/wait.h
Macro Defination
WIFEXITED(stat_val) Nonzero if child terminated normally
WEXITSTATUS(stat_val) If WIFEXITED is nonzero, this returns child exit code
WIFSIGNALED(stat_val) Nonzero if child is terminated on an uncaught signal
WTERMSIG(stat_val) If WIFSIGNALED is nonzero, this returns signal number
WIFSTOPPED(stat_val) Nonzero if the child has stopped
WSTOPSIG(stat_val) If WIFSTOPPED is nonzero, this returns signal number
- The wait() is used when a result of process done by child is used by the parent for further processing.
- For eg :-
In a program child process write to file1 and parent has to read from (the written data of)file1.
If the scheduler runs read() command of the parent process before the write() command of child process, it reads nothing.
- So, wait() is used before read() statement in parent process to avoid the unnecessory error.