Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do multiple fork statements work?

Tags:

c

fork

unix

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 ?

like image 749
asheeshr Avatar asked Dec 20 '22 10:12

asheeshr


1 Answers

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.

like image 192
hyde Avatar answered Dec 24 '22 02:12

hyde