Consider the following code snippet using the fork() and wait() system calls.…
2024
Consider the following code snippet using the fork() and wait() system calls. Assume that the code compiles and runs correctly, and that the system calls run successfully without any errors.
int x = 3;
while(x > 0) {
fork();
printf("hello");
wait(NULL);
x--;
}
The total number of times the printf statement is executed is _______
Attempted by 197 students.
Show answer & explanation
Correct answer: 14
Key idea: set f(n) = total number of times printf runs starting from one process with x = n.
In the first loop iteration fork() creates two processes and both execute printf once, contributing 2 prints.
Because the parent calls wait(NULL) after fork, the child runs (and finishes its remaining work) before the parent resumes. Each of the child and then the parent will independently produce f(n-1) additional prints.
Therefore the recurrence is f(n) = 2 + 2·f(n-1) with base f(0) = 0.
Compute for n = 3: f(1) = 2, f(2) = 6, f(3) = 14. So printf runs 14 times.
A video solution is available for this question — log in and enroll to watch it.