A process executes the following C code. Assume that every fork() call…

2023

A process executes the following C code. Assume that every fork() call succeeds.

for (i = 1; i <= 3; i++)
    fork();
fork();

How many new processes are created?

Answer: D. 15Concept: Each call to fork() creates an exact duplicate of the calling process, and both the parent and the new child continue execution from the point right…

  1. A.

    64

  2. B.

    63

  3. C.

    16

  4. D.

    15

Attempted by 118 students.

Show answer & explanation

Correct answer: D

Concept: Each call to fork() creates an exact duplicate of the calling process, and both the parent and the new child continue execution from the point right after that fork() call. So every fork() statement that lies on a path every existing process will reach doubles the total number of process instances at that point — the growth is exponential in how many times a fork() call-site is reached along the execution path, not simply in how many fork() statements are written in the code.

Application: trace the process count step by step.

  1. Because the for-loop has no braces, only the statement immediately after the loop header belongs to the loop body — here that is the first fork(); line. This statement is reached three times, once per loop iteration (i = 1, 2, 3).

  2. Iteration 1: the 1 existing process reaches fork() and becomes 2 processes. Iteration 2: both of those processes reach fork() and become 4 processes. Iteration 3: all four processes reach fork() and become 8 processes. So 8 process instances exist once the loop finishes.

  3. The second fork(); line sits outside the loop, so it is a separate statement executed once by every process that reaches it. All 8 existing instances independently execute it, doubling the population once more: 8 → 16 process instances.

  4. New processes created = total instances after the code runs, minus the single original process that started execution = 16 − 1 = 15.

Cross-check: in general, if a straight-line sequence of n fork() call-sites is reached by every process that exists at that point, the total instance count is 2n and the new processes created equal 2n − 1. Here n = 3 (from the loop) + 1 (the standalone statement) = 4, giving 24 − 1 = 15, matching the step-by-step trace above.

Result: 15 new processes are created.

Explore the full course: Cdac C Cat Complete Preparation

Loading lesson…