Question

Consider the following program snippet. Assume that the program compiles and runs successfully. Further, assume that the fork() system call is always successful in creating a process.

int main () {
   int i;
   for (i = 0; i < 3; i++){
      if (fork() == 0){
        continue;
      }
      break;
   }
   printf("Hello!");
   return 0;
}

The total number of times that the printf statement gets executed is ________. (answer in integer)

Official answer and solution
Official answer
4
From
Official GATE 2026 answer key

Solution

Trace the control flow of parent (fork() != 0, which hits break) versus child (fork() == 0, which hits continue) in each loop iteration.

In each iteration i∈{0,1,2}i \in \{0, 1, 2\}:

  • The calling (parent) process receives a non-zero PID from fork(), skips the if body, executes break;, exits the for loop immediately, and executes printf("Hello!");.
  • The newly created child process receives 0 from fork(), executes continue;, and advances to the next iteration of the loop.

Thus:

  • i=0i = 0: Initial process P0P_0 spawns child P1P_1 and breaks out of the loop.
  • i=1i = 1: P1P_1 spawns child P2P_2 and breaks out of the loop.
  • i=2i = 2: P2P_2 spawns child P3P_3 and breaks out of the loop; P3P_3 increments ii to 33 and terminates the loop normally.

All 44 processes (P0,P1,P2,P3P_0, P_1, P_2, P_3) execute printf("Hello!"); once, for a total of 4 times.

Final answer

4

Common trap

Assuming 23=82^3 = 8 processes are created by overlooking the break; statement executed by the parent.

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

Source

Paper
GATE 2026 Computer Science and Information Technology - Session 1 (CS1)
Question
63 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.