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

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
collegedunia
Verified By Collegedunia

Correct Answer: 4

Solution and Explanation

Step 1 (Concept): fork() creates a new process. In the parent process, fork() returns the child's process id (a nonzero value); in the newly created child process, fork() returns 0. After the call, both processes continue executing independently from the statement right after fork().

Step 2 (Iteration i = 0, process P0 active): P0 calls fork(), creating child C1. In P0, fork() returns nonzero, so the if-condition is false, and P0 executes break, leaving the loop. In C1, fork() returns 0, so the if-condition is true, and C1 executes continue: i becomes 1, and since 1 < 3, C1 continues into the next iteration. P0, having broken out, falls through to printf("Hello!") and prints once.

Step 3 (Iteration i = 1, process C1 active): C1 calls fork(), creating child C2. In C1, fork() returns nonzero, so C1 executes break and falls through to printf, printing once. In C2, fork() returns 0, so C2 executes continue: i becomes 2, and since 2 < 3, C2 continues.

Step 4 (Iteration i = 2, process C2 active): C2 calls fork(), creating child C3. In C2, fork() returns nonzero, so C2 executes break and falls through to printf, printing once. In C3, fork() returns 0, so C3 executes continue: i becomes 3.

Step 5 (Loop check for C3): i = 3 fails the condition i < 3, so C3 exits the loop naturally (not via break) and falls through to printf, printing once.

Step 6 (Count all processes): Exactly 4 processes ever exist: P0, C1, C2, C3 - one fork() call happens per loop iteration (3 total), each creating exactly one new process, since the process that breaks out at each level never loops back and never forks again. Every one of these 4 processes reaches the single printf statement (three via break, one via the loop condition failing) and executes it exactly once.

Step 7: Total number of printf executions = number of processes = 4.

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

Top GATE CS Operating System Questions

View More Questions