Search code examples
cfor-loopfork

C program-fork command in a for loop


I am writing a C program that uses a fork command and loops 10 times, at the same time, the process ID will be displayed in each loop.

Following are my codes:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

main ()
{ int x;
  for(x=0;x<10;x++)
  {
   fork();
   printf("The process ID (PID): %d \n",getpid());
  }
}

My codes generate numerous of process ID,is there anything wrong in the program?


Solution

  • fork() system call creates a child which executes the same code as the parent. From that moment, there are 2 processes executing the next line: parent and child. Each of them executes the printf().

    The second time the for loop is executed, it is executed by the parent and the child: each of them execute fork(), and so from that moment there are 4 processes: the 2 first ones, and their new children.

    So, for every iteration in the loop you are doubling the number of processes. The total number of processes is thus 2^10 = 1024.

    So, the printf() inside the for loop is executed:

    • 10 times for the first 2 processes
    • 9 times for their children (2 processes)
    • 8 times for the next generation (4 new children)
    • 7 times for the next one (8 children)
    • 6 times fot the next one (16 children)
    • 5 times for the next one (32 children)
    • 4 times for the next one (64 children)
    • 3 times for the next one (128 children)
    • 2 times for the next one (256 children)
    • 1 time for the last one (512 children)

    Total: 10*2 + 9*2 + 8*4 + 7*8 + 6*16 + 5*32 + 4*64 + 3*128 + 2*256 + 1*512 = 2046.

    The printf() is executed 2046 times.