IAE Academy

GATE 2024 CS1 Q.57: solution and answer

GATE 2024 · CS1Q.57 · 2 marks · NAT

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 _______

See the question in the paper

Answer and solution

ANSWER

The printf statement is executed 14 times in total.

Official answer: 14Source: Official answer key, GATE 2024 CS1 (IISc Bengaluru)

  1. Each fork() creates a child that is an exact copy of the parent, including the current value of x. After the fork, the parent and the child each run printf, then wait(NULL), then x--, then test the loop condition again.

  2. Let be the total number of printf executions made by one process that enters the loop with value , counting everything its descendants print. When the loop does not run, so .

  3. In one iteration, the parent and the child each execute printf once. That gives 2 prints.

  4. After the iteration both processes hold and both return to the loop test. Each of them then produces prints. wait(NULL) only delays the parent until its child ends (the child, having no children yet, gets an immediate return from its own wait). It does not change the count.

  5. So .

  6. Check by process count: iteration 1 has 1 process, which forks, so 2 prints. Iteration 2 has 2 processes, each forks, so 4 prints. Iteration 3 has 4 processes, each forks, so 8 prints. The total is .

KEY IDEA

Every fork copies the process, including x, so each iteration doubles the number of processes, and every process prints once per iteration. Prints per iteration are 2, 4, 8, which total 14.

WATCH OUT FOR

Counting only the parent's prints, or thinking that wait(NULL) stops the child from reaching later iterations. Another slip is to assume the child restarts with the original x. The child keeps the current x and joins the loop with it.

From the GATE 2024 CS1 paper. Every question of this paper · Download the full paper · All 9 Processes & threads questions, with notes

More Processes & threads questions