Wait System Call

A call to wait( ) blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, parent continues its execution after wait system call instruction.
Child process may terminate due to any of these:

  • It calls exit( );
  • It returns (an int) from main
  • It receives a signal (from the OS or another process) whose default action is to terminate.

If any process has more than one child processes, then after calling wait(), parent process has to be in wait state if no child terminates.

If only one child process is terminated, then return a wait() returns process ID of the terminated child process.

If more than one child processes are terminated than wait( ) reap any arbitrarily child and return a process ID of that child process.
When wait() returns they also define
exit status (which tells our, a process why terminated) via pointer, If status are not NULL.

If any process has no child process then wait() returns immediately “-1”.

Examples:

C program to demonstrate working of wait( ) #include<stdio.h> #include<stdlib.h> #include<sys/wait.h> #include<unistd.h> int main(  ) {     pid_t cpid;     if (fork()==0)         exit(0);                   /* terminate child */     else         cpid= wait(NULL); /* reaping parent */     printf("Parent pid = %d\n", getpid());     printf("Child pid = %d\n", cpid);     return 0; }

Output:

Parent pid = 12345678 
Child pid = 89546848 
C program to demonstrate working of wait( ) #include<stdio.h> #include<sys/wait.h> #include<unistd.h> int main( ) {     if (fork( )==0)         printf("HC: hello from child\n");     else     {         printf("HP: hello from parent\n");         wait(NULL);         printf("CT: child has terminated\n");     }     printf("Bye\n");     return 0; }

Output: depend on environment

HC: hello from child
HP: hello from parent
CT: child has terminated
     (or)
HP: hello from parent
HC: hello from child
CT: child has terminated    // this sentence does 
                            // not print before HC 
                            // because of wait.

Child status information:
Status information about the child reported by wait is more than just the exit status of the child, it also includes

  • normal/abnormal termination
  • termination cause
  • exit status

For find information about status, we use
WIF….macros

1. WIFEXITED(status)      : child exited normally
WEXITSTATUS(status)  : return code when child exits

2. WIFSIGNALED(status) : child exited because a signal was not caught
WTERMSIG(status)        : gives the number of the terminating signal

3. WIFSTOPPED(status)   : child is stopped
WSTOPSIG(status)         : gives the number of the stop signal

Leave a comment