How do multiple fork statements work?

16,300

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.

Share:
16,300
asheeshr
Author by

asheeshr

New to Stack Exchange? See my short guide on the basics. If you are participating on a beta site, then The Real Essential Questions of Every Beta is an important resource to read! Some of my work can be found on Github.

Updated on June 17, 2022

Comments

  • asheeshr
    asheeshr almost 2 years

    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 ?