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)
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:
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 chainLet \(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 countEvery 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