3

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.

Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44

2 Answers2

2

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Try this piece of code.

The output of this code will explain alot more things to you. Some of the processes print their respective printf function after their parent process died. These processes(orphan process) are adopted by some other processes. That could be the reason for a peculiar pid being printed by printf function. Also, there is a race-condition between creation of processes and printing of their respective pid which can be seen in the output of the code below.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    printf("Main\n");
    for(int i=0;i<3;i++) {
        printf("Loop index - %d and pid is - %d\n", i, getpid());
        int cpid=fork();
        if(cpid==0) 
             printf("I am a child with id %d, and my parent is %d with loop index - %d\n",getpid(),getppid(), i);
        else
              printf("I am a parent with id %d and with loop index - %d\n",getpid(), i);
    }
    printf("Terminated - %d\n", getpid());
    return 0;
 }
abhiarora
  • 9,743
  • 5
  • 32
  • 57