A process executes the following code for (i = 0; i < n; i++) fork(); The…

2008

A process executes the following code

for (i = 0; i < n; i++) fork();

The total number of child processes created is

  1. A.

    n

  2. B.

    2n - 1

  3. C.

    2n

  4. D.

    2(n+1) - 1

Attempted by 151 students.

Show answer & explanation

Correct answer: B

Answer: 2^n - 1

Explanation: Each call to fork() causes every existing process to create one new child, so the total number of processes doubles on every iteration. Starting with a single process:

  • After 1st iteration: 2^1 total processes (1 child created).

  • After 2nd iteration: 2^2 total processes (3 children created in total).

  • After n iterations: 2^n total processes, so child processes = 2^n - 1.

Therefore, the total number of child processes created by the loop is 2^n - 1.

Why the other answers are incorrect:

  • 'n' assumes one child per loop iteration overall, but forks happen in every existing process, so growth is exponential.

  • '2^n' gives the total processes including the original parent, not the number of child processes.

  • '2^(n+1) - 1' corresponds to one extra fork and therefore overcounts the children.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir