Question

Consider the following code snippet using the fork() and wait() system calls. Assume that the code compiles and runs correctly, and that the system calls run successfully without any errors.

int x = 3;
while(x > 0) {
  fork();
  printf("hello");
  wait(NULL);
  x--;
}

The total number of times the printf statement is executed is _______

Official answer and solution
Official answer
14
From
Official GATE 2024 answer key

Solution

Count the number of active processes after each fork() call across the 3 loop iterations (x = 3, 2, 1).

Tracing the number of processes executing the loop body across each value of x:

  • Iteration 1 (x = 3): 11 initial process calls fork(), resulting in 22 processes. Both execute printf("hello") (2 times) and decrement their copy of x to 22.
  • Iteration 2 (x = 2): All 22 processes call fork(), resulting in 44 processes. All 44 execute printf("hello") (4 times) and decrement x to 11.
  • Iteration 3 (x = 1): All 44 processes call fork(), resulting in 88 processes. All 88 execute printf("hello") (8 times) and decrement x to 00, terminating the loop.

Total number of times printf is executed =2+4+8=14= 2 + 4 + 8 = 14.

Final answer

14

Common trap

Confusing the total number of printf executions (2+4+8=142 + 4 + 8 = 14) with the final number of processes (23=82^3 = 8) or child processes (23−1=72^3 - 1 = 7).

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 1 (CS1)
Question
57 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.