Search code examples
processforkpid

why are parent.getpid() and child.getppid() different


I am trying to understand the consept of process. So I wrote a program like this:

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main() {
  pid_t  pid;
  pid = fork();
  if (pid == 0)
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
  else
    printf("This is the parent process. My pid is %d and my child's id is %d.\n", getpid(), pid);
}

I expected this program would print something like

This is the parent process. My pid is 2283 and my child's id is 2284.
This is the child process. My pid is 2284 and my parent's id is 2283.

But instead, it prints this

This is the parent process. My pid is 2283 and my child's id is 2284.
This is the child process. My pid is 2284 and my parent's id is 1086.

At the end of the second line, the parent pid of the child is different form the parent process's pid. Why is this happening? Is there something that I am missing?

Thanks in advance


Solution

  • The hint of Tony Tannous was correct: The child may live longer than the parent. When the parent is exiting its child process is "hung up" i.e. it becomes child process of the init process.

    I modified the sample code of OP to force the child process living longer then the parent process.

    #include<stdio.h>
    #include<sys/types.h>
    #include<unistd.h>
    
    int main()
    {
      pid_t  pid;
      pid = fork();
      if (pid == 0) {
        sleep(1); /* 1 s */
        printf(
          "This is the child process."
          " My pid is %d and my parent's id is %d.\n", getpid(), getppid());
      } else {
        printf(
          "This is the parent process."
          " My pid is %d and my child's id is %d.\n", getpid(), pid);
      }
      return 0;
    }
    

    Compiled and tested with gcc on cygwin:

    $ gcc -o test-pid-ppid test-pid-ppid.c
    
    $ ./test-pid-ppid
    This is the parent process. My pid is 10748 and my child's id is 10300.
    
    $ This is the child process. My pid is 10300 and my parent's id is 1.
    

    In my test this is obvious due to the specific PID 1 (the PID the init process usually gets). I'm a little bit surprised about PID 1086 observed in the OP but:

    1. There is no specification (I know) that init process must get PID 1 - its only usual.
    2. The OP was run on a VM. There, may be, things are done slightly different than usual...

    Concerning my belief that an exiting process would kill all of its children, I investigated further and found this: Is there any UNIX variant on which a child process dies with its parent?. In short: my belief was wrong. Thank's for that question which forced me to enlightment.