Search code examples
processfork

Does the grandparent process of a child process becomes its parent if its parent ends


Suppose I have at the following program

 for(i=0; i<3; i++)
 pid = fork();

My understanding is that 8 processes will be created once the for loop iterates. Processess

Now suppose the Highlighted Process gets terminated, will the First Parent Process, end up becoming the parent of the other 2 processes and the Grandparent of the Last Process in the chain?


Solution

  • No, a process does not become the parent of its children's children or their descendents.

    After a parent process terminates, children of that deceased parent immediately become children of a specific system-designated process.

    Traditionally that system-designated process was a single, system-wide process known as init. One of that process's responsibilities was to "reap" (collect the exit status of) orphaned processes when they eventually terminate. Traditionally that init process had a process ID equal to 1.

    However, over the last few years it has become common to have multiple init processes in addition to, or perhaps instead of, the original PID=1 init. For instance, the processes running in a container or in a user login session might be given their own dedicated init process. So on a modern system it's possible for your orphaned child processes to end up with a parent PID that is not 1.

    The answer at https://unix.stackexchange.com/a/177361/18253 goes into much more detail on this.