Skip to main content

Command Palette

Search for a command to run...

Wait in Operating System

Updated
2 min readView as Markdown
Wait in Operating System
  • wait()-> Parent process waits until child process completes its execution.

  • It return the PID of the child process that terminated.

Example1: without wait()

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

int main(int argc, char const *argv[])
{
    printf("Hello This is Wait System Call in OS %d\n", getpid());
    int rc = fork();

    if(rc < 0){
        printf("Child process failed %d\n", getpid());
    }
    else if (rc == 0){
        printf("This is a child process %d\n", getpid());
    }
    else{
        printf("This is a parent process %d having child %d\n", getpid(), rc);
    }

    return 0;
}

  • Suppose parent id : 515

  • Parent calls for child process using fork

  • Parent process continues its execution and print the else statement from code

  • Child process print statement executed at last

Example 2: with wait

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

int main(int argc, char const *argv[])
{
    printf("Hello This is Wait System Call in OS %d\n", getpid());
    int rc = fork();

    if(rc < 0){
        printf("Child process failed %d\n", getpid());
    }
    else if (rc == 0){
        printf("This is a child process %d\n", getpid());
    }
    else{
        int wc = wait(NULL);
        printf("This is a parent process %d having child %d\n", getpid(), rc);
        printf("Wait returned %d\n", wc);
    }


    return 0;
}

  • Suppose parent id : 506

  • Parent calls for child process using fork

  • Parent process wait until child process completed

  • Child process print statement executed.

  • Now parent process resumes and executes its remaining statements.

Wait return and argument

wait(NULL)-> Parent process waits until any child process completes its execution.

  • wait(&status)-> stores information how child process terminated.

    • int status;

    • pid_t pid = wait(&status);

  • Pid: stores the PID of child process

  • Status: stores exit code and status info

Common macros for interpreting status

Marco

Description

Example

WIFEXITED(status)

True if child exited normally (via exit() or return)

if (WIFEXITED(status)) printf("Exit code: %d", WEXITSTATUS(status));

WEXITSTATUS(status)

Return the exit code passed by child

0,1,etc.

WIFSIGNALED(status)

True if child terminated due to signal

killed by SIGKILL

WTERMSIG(status)

Returns the signal number that caused termination

9 for SIGKILL

WIFSTOPPED(status)

True if child is stopped