Coursal
Coursal

Reputation: 1387

Unix: Forks to a tree

I'm a newbie at unix shell programming and I have a really hard time getting an good explanation about forks and their trees. All I know for now is that a fork kind of copies a process (child) from the main one (parent).

More specifically I can't quite get from a piece of code how a process tree would be like.

For example, at this backbone of code:

pid1=fork();
if (pid1!=0) 
{   
    pid2=fork(); 
    pid3=fork(); 
}
else 
{ 
    pid4=fork(); 
} 

It seems to me that there are 3 processes under the original process (pid1, pid2, pid3) and a child of one of these three (pid4), maybe pid2's.

I tried to run it with some more awfully written code:

int pid1, pid2, pid4, pid4;

printf("I'm the original Process %d with parent %d \n", getpid(), getppid());

pid1=fork();

if(pid1!=0)
{
    pid2=fork();
    printf("I'm P2 %d with parent %d \n", getpid(), getppid());
    sleep(1);

    pid3=fork();
    printf("I'm P3 %d with parent %d \n", getpid(), getppid());
    sleep(1);
}
else
{
    pid4=fork();
    printf("I'm P4 %d with parent %d \n", getpid(), getppid());
    sleep(1);
}

Edit: I put some sleep(1) at the code above, thanks to dbush, so I can see the ppid's

enter image description here

So, how is the tree forming with these types of code?

Upvotes: 1

Views: 665

Answers (1)

dbush
dbush

Reputation: 223872

You'll get a total of 5 children:

                  c2--------------
                    |             
                    |             
     c1---------------------------
       |           p4             
       |                          
       |                          
       |                          
       |                c5--------
       |                  |       
       |                  |       
       |       c3-----------------
       |         |       p3       
       |         |                
       |         |      c4--------
       |         |        |       
       |         |        |       
p---------------------------------
      p1        p2       p3

The first fork happens at point p1, which create child c1. This child goes into the else part of the code and runs the fork at point p4, creating child c2.

Back in the parent, it forks at point p2 creating child c3. Both of these processes then fork at point p3, creating children c4 and c5.

The reason you're seeing some processes report their parent as 1 is because the parent is finishing before the child. Try putting sleep(1) at the bottom of this block to give the parent processes time to stay around so the children can see them.

Upvotes: 2

Related Questions