Search code examples
cfork

Why does this ppid == 1? Am I missing something about fork()?


#include <stdio.h>

int main(void)
{
    fork();
    fork();
    printf("ppid %d pid %d\n", getppid(), getpid());
    return 0;
}

The above code sometimes prints

$ ./a.out 
ppid 3389 pid 3883
ppid 3883 pid 3885
ppid 1 pid 3884
ppid 3884 pid 3886

Why is process 3884's ppid 1? Doesn't it supposed to be 3883?


Solution

  • I'd guess the parent process had already completed running and exited by the time the third child checked for the parent's PID. That would have caused the child to be re-parented under init, which has process ID 1.