asheeshr
asheeshr

Reputation: 4114

How do multiple fork statements work?

If I run the following code :

#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid, pid1;
    fflush(stdout);
    pid = fork();
    fflush(stdout); 
    pid1 = fork();
    if(pid==0)
    {
         printf("%d is the first child\n", getpid() );
    }
    else if(pid>0)
    {
         printf("%d is the first parent\n", pid);
        wait();
    }
    if(pid1==0)
    {
         printf("%d is the second child\n", getpid() );
    }
    else if(pid1>0)
    {
         printf("%d is the second child\n", pid1);
        wait();
    }

    return 0;
}

I get the output :

2896 is the first parent
2896 is the first child
2898 is the first child
2898 is the second child
2898 is the second child
2896 is the first parent
2897 is the second child
2897 is the second child

I cannot understand the output. Why are the same strings being printed multiple times ?

Upvotes: 5

Views: 19758

Answers (3)

Aarhi
Aarhi

Reputation: 11

For better understanding, you can write your if/else block for each process:

    if(pid != 0 && pid1 != 0){
        printf("Parent P\n");//parent
    }else if(pid == 0 && pid1 != 0){
        printf("First child of P\n");
    }else if(pid != 0 && pid1 == 0){
        printf("Second child of P\n");
    }else{
        //pid = 0, pid2 = 0
        printf("Child of the first child of P\n");
    } 

Upvotes: 1

&#246;mer Deveci
&#246;mer Deveci

Reputation: 1

Also i think you print same string mistakenly in this code below

else if(pid1>0)
{
    printf("%d is the second child\n", pid1); // This "child" should be "parent"
    wait();
}

Upvotes: 0

hyde
hyde

Reputation: 62777

You are doing total 3 forks: First, pid = fork() is done in original process, resulting in one more process, so total is now two, both continuing from the next line in your code.

Then pid1 = fork() is done on both of these, resulting in two more child processes, so total is now 4, each again continuing to next line (first if).

Then all three processes process the two if-else statements (assuming no fork errors), each process printing two lines. So four processes times 2 lines is 8 lines. Which you are getting.

So the processes are:

  • original
  • first generation older child, from 1st fork statement
  • first generation younger child, from 2nd fork statement by the original
  • 2nd generation child, from 2nd fork statement by the older first generation child

If you want to understand the output, step through the code in your mind for all of these four processes. It might also help if you print out current pid in each print statement, in addition to what you print now.

Upvotes: 11

Related Questions