Search code examples
cforkpidwaitpid

Parameters of the waitpid()


#include<stdio.h>   
#include<sys/types.h>   
#include<unistd.h>  

int main() 
{
    int status; 
    int pid = fork();assigned to variable "pid"

    if(pid == 0)    
    {
        printf("I am the child with pid = %d\n", getpid()); 
    }
    else
    {
        printf("I am the parent with pid = %d\n", getpid()); 
        waitpid(pid, &status, 0); // line 51
    }
    return 0;
}

In line number 51, please clarify the "pid" parameter. what will this process wait for?


Solution

  • fork returns 0 for the child process, -1 on error, and something else for the parent process. The else begins the part for the parent process, that means pid in waitpid contains the child's PID.

    Citing man wait:

    The waitpid() system call suspends execution of the calling process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is mod- ifiable via the options argument [...]

    In short, waitpid waits for the child process to terminate.