Question:medium

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 ________.

Show Hint

Remember fork() returns 0 in the child and a nonzero value in the parent. Trace each independent process through the loop - only the child that takes continue stays inside the loop and forks again.
Updated On: Jul 22, 2026
Show Solution

Correct Answer: 4

Solution and Explanation

Step 1 (Alternate method - explicit process enumeration by fork call): Label every process by which fork() call created it, and note that at each iteration exactly one process is still active inside the loop (the one that took the fork() == 0, continue branch); every other process produced at that step immediately leaves via break.

Step 2 (Fork call 1, i = 0): The original process (Proc-0) forks. Proc-0 itself gets a nonzero return, executes break, and is now finished with the loop. The new child (Proc-1) gets 0, executes continue, and moves on with i = 1.

Step 3 (Fork call 2, i = 1): Proc-1 forks. Proc-1 gets nonzero, executes break, and is finished with the loop. The new child (Proc-2) gets 0, executes continue, and moves on with i = 2.

Step 4 (Fork call 3, i = 2): Proc-2 forks. Proc-2 gets nonzero, executes break, and is finished with the loop. The new child (Proc-3) gets 0, executes continue, and moves on with i = 3, at which point the loop condition i < 3 fails and Proc-3 exits the loop as well.

Step 5 (Total process list): Proc-0, Proc-1, Proc-2, Proc-3 - exactly 4 processes in total (1 original + 3 new children, one per loop iteration, since a process that breaks never forks a second time).

Step 6: printf("Hello!") sits after the loop with no condition around it, so every one of the 4 processes executes it exactly once when it reaches that point, whether it arrived there via break or via the loop condition becoming false.

Step 7: Total printf executions = 4 processes x 1 printf each = 4.

\[ \boxed{4} \]
Was this answer helpful?
0

Questions Asked in GATE CS exam