2

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?

alk
  • 69,737
  • 10
  • 105
  • 255
  • `int pid;` should be defined as `pid_t pid;` Have the parent `waitpid()` on the child, so the parent is still running when the child calls `getppid()`. The `fork()` function has three returns: =0 means child, >0 means parent, <0 means error. Always check all three conditions, do not assume the operation was successful – user3629249 Sep 27 '15 at 16:28

1 Answers1

7

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;
}
Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612