Prashant Pandey Prashant Pandey - 3 months ago 12
Linux Question

Process and child creation by forking: unexplainable behaviour

I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
for(int i=0;i<3;i++)
{
int cpid=fork();
if(cpid==0)
printf("I am a child with id %d, and my parent is %d\n",getpid(),getppid());
else
printf("I am a parent with id %d\n",getpid());
}
}


I am trying to form a process tree. The output is:

I am a parent with id 9494
I am a parent with id 9494
I am a child with id 9495, and my parent is 9494
I am a parent with id 9494
I am a child with id 9496, and my parent is 9494
I am a parent with id 9495
I am a parent with id 9496
I am a parent with id 9495
I am a child with id 9498, and my parent is 9495
I am a parent with id 9498
I am a child with id 9499, and my parent is 3004
I am a child with id 9497, and my parent is 3004
I am a child with id 9500, and my parent is 3004
I am a child with id 9501, and my parent is 3004


I cannot figure out where is the process with id 3004 coming in. How many total processes are created as a result of this code? What will be the final process tree? I am beginner.

NPE NPE
Answer

I'll help with the mystery of process 3004. The rest should be reasonably easy to figure out on your own (you might want to add cpid to the second printf() to help with that).

I am a child with id 9499, and my parent is 3004

What happened here is that the original parent of process 9499 had died before 9499 had a chance to call getppid(). When the parent of a process dies, that process gets re-parented. In your case, the new parent's pid is 3004. This process is not part of the process tree created by your program (it probably sits somewhere above it in the overall process tree), so you don't see a "I am a parent with id" for it.

Here is some relevant reading: process re-parenting: controlling who is the new parent.