Skip to content
GATEiit

GATE CSE 2024 Session 1 Q57: printf count for fork() inside a loop with wait()

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 _______

Try it: numerical answer: type the value

Numerical answer. No negative marking.
Show answer and explanation

Answer: 14 (official GATE 2024 final answer key)

Concept used: Each fork doubles the number of processes that continue through the rest of the loop body.

First step: Count processes printing in each iteration: 2 in the first, then 4, then 8.

Full step-by-step solution

Detailed working, common mistakes and linked mock tests will be available with a free GATEiit account. Log-in is coming soon.

Share this question

WhatsAppDownload image

Source: official GATE 2024 Session 1 CS question paper and final answer key, organised by IISc Bangalore. Question paper · Answer key