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 ________.
(answer in integer)

Show Hint

At each fork(), the parent (nonzero return) always breaks out and prints immediately, while only the child (0 return) continues the loop and can fork again. So the forks form a straight chain, not a tree: 3 fork() calls give 3 children plus the original process = 4 processes, each printing once.
Updated On: Aug 3, 2026
Show Solution

Correct Answer: 4

Solution and Explanation

An alternative way to see it: think of a fork chain, not a fork tree

A naive guess is that fork() inside a loop creates an exponential process tree (like \(2^n\) processes), but that only happens when *both* parent and child keep looping. Here the control-flow forces exactly one of the two branches to stop immediately:

  • if fork() returns nonzero (you are a parent), the if-check fails and break fires -- this process exits the loop for good.
  • if fork() returns 0 (you are a child), continue fires -- this process is the only one that gets to run the next loop iteration.

So at every iteration, only a single 'surviving' process is left to call fork() again; the other one (the parent from that step) drops out of the loop and heads straight for printf(). This turns the process growth into a straight chain rather than a branching tree.

Counting the chain

Let \(P_0\) be the original process. \(P_0\) forks once at \(i=0\), producing child \(C_1\); \(P_0\) itself then breaks and prints. \(C_1\) becomes the new 'active' process at \(i=1\), forks to produce \(C_2\), and \(C_1\) itself breaks and prints. \(C_2\) becomes active at \(i=2\), forks to produce \(C_3\), and \(C_2\) breaks and prints. Now \(C_3\) is active with \(i\) about to become \(3\); since the condition \(i < 3\) fails, \(C_3\) leaves the loop without forking again and prints.

So the chain of forking processes is \(P_0 \to C_1 \to C_2 \to C_3\), giving exactly \(3\) fork() calls and \(3+1 = 4\) total processes (the original plus the three children).

Why the printf count equals the process count

Every one of these 4 processes reaches the printf() statement exactly once -- there is no path through the code that lets a process call printf() more than once, and no process is ever silently lost (fork() is guaranteed to succeed here). Hence:

\[\text{printf() executions} = \text{number of processes} = 4\]

Final Answer: 4

Was this answer helpful?
0


Questions Asked in GATE CS exam