rader craft
rader craft

Reputation: 33

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?

Upvotes: 3

Views: 4933

Answers (2)

Juan Cespedes
Juan Cespedes

Reputation: 1363

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.

Upvotes: 7

user1990
user1990

Reputation: 546

check my exemple

  pid_t pID = fork();
       if (pID == 0)                // child
       {
          // Code only executed by child process

          sIdentifier = "Child Process: ";
          globalVariable++;
          iStackVariable++;
    }
        else if (pID < 0)            // failed to fork
        {
            cerr << "Failed to fork" << endl;
            exit(1);
            // Throw exception
        }
        else                                   // parent
        {
          // Code only executed by parent process

          sIdentifier = "Parent Process:";
        }

        // Code executed by both parent and child.

Upvotes: 0

Related Questions