Search code examples
cfor-loopoperating-systemforkparent-child

fork() in a for loop with 2 iterations


What will be the output of the following code:

#include <stdio.h>

void main()
{
int i;

for (i=0;i<2;i++)
{
    fork();

    printf("1\n");
}

printf("2\n");

}

On the lectures, the professor ran the code and the output had six 1s and four 2s, but I don't understand how we obtained those numbers.


Solution

  • Lets "draw" the processes in a tree form, and mark out where the printf call are happening, and then count the printf calls of each type:

                          parent
                            |
                          fork
                            ^
             parent -------/ \------------ child
               |                             |
            printf("1")                   printf("1")
               |                             |
         loop iterates                 loop iterates
               |                             |
              fork                          fork
               ^                             ^
     parent --/ \----- grandchild   child --/ \----- grandchild
       |                  |           |                 |
    printf("1")       printf("1")  printf("1")       printf("1")
       |                  |           |                 |
    loop ends         loop ends    loop ends         loop ends
       |                  |           |                 |
    printf("2")       printf("2")  printf("2")       printf("2")
       |                  |           |                 |
    proc ends         proc ends    proc ends         proc ends
    

    As we can see there are six printf("1") calls, and four printf("2") calls.

    [I haven't added the newlines in the printf calls, the diagram only is for counting the number of calls. Actual output may differ depending on buffering depending on stdout target.]