cshellunixforkprocess-reaper

Fork command in shell to print process ids


I am trying to print the pid of the processes after running the fork() command. Here is my code-

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int pid;
    pid=fork();
    if(pid==0)
        printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
    else
        printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
    return 0;
}

This is the answer I am getting-

I am the parent.My pid is 2420. My childs pid is 3601 
I am the child.My pid is 3601 .My parents pid is 1910 

Why is the parents id in 2nd line not 2420.Why am I getting 1910 How can I get this value?


Solution

  • The parent is exiting before the child performs its printf call. When the parent exits, the child gets a new parent. By default this is the init process, PID 1. But recent versions of Unix have added the ability for a process to declare itself to be the "subreaper", which inherits all orphaned children. PID 1910 is apparently the subreaper on your system. See https://unix.stackexchange.com/a/177361/61098 for more information about this.

    Put a wait() call in the parent process to make it wait for the child to exit before it continues.

    #include <stdio.h>
    #include <unistd.h>
    
    int main(void)
    {
        int pid;
        pid=fork();
        if(pid==0) {
            printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
        } else {
            printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
            wait(NULL);
        }
        return 0;
    }