GATE CS 2024 Set 1 | Question 57

NAT · 2 marks

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 _______

Answer

14

Explanation

After each fork(), the parent and the new child both call printf once and then continue the loop with the same value of x. So every pass doubles the number of processes, and each of them prints once:

  • \(x = 3\): 2 processes print.
  • \(x = 2\): 4 processes print.
  • \(x = 1\): 8 processes print.

The total is \(2 + 4 + 8 = 14\). wait(NULL) only makes a parent wait for its children; it changes the order of execution, not the count. (More than 14 copies of "hello" can finally appear, because fork() copies unflushed output; the question counts executions of the statement.)

Answer: 14