Write a C Program Using Wait System Call

Aim:

To write a C Program Using Wait System Call.

Description:

  • The system call wait() is blocks the calling process until one of its child processes exits or a signal is received.
  • For our purpose, we shall ignore signals. wait() takes the address of an integer variable and returns the process ID of the completed process.
  • Some flags that indicate the completion status of the child process are passed back with the integer pointer. One of the main purposes of wait() is to wait for the completion of child processes.

The execution of wait() could have two possible situations.

  1. If there are at least one child processes running when the call to wait() is made, the caller will be blocked until one of its child processes exits. At that moment, the caller resumes its execution.
  2. If there is no child process running when the call to wait() is made, then this wait() has no effect at all. That is, it is as if no wait() is there.

Algorithm:

  • STEP 1- START
  • STEP 2- Declare the pid t cpid
  • STEP 3- Use the fork child process
  • STEP 4- Use exit is terminate chid
  • STEP 5- cpid is reaping parent
  • STEP 6- print the parent pid and child pid
  • STEP 7- STOP

Program:

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

int main()
{
pid_t cpid;
if (fork()== 0)
exit(0);
else
cpid = wait(NULL); 
printf("Parent pid = %d\n", getpid());
printf("Child pid = %d\n", cpid);
return 0;
}

Execution:

parent pid  = 20302
child pid = 20303

Result:

Thus wait system call program was executed Successfully.

Leave a Comment