Question
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 _______
Official answer and solution
- Official answer
- 14
- From
- Official GATE 2024 answer key
Solution
Count the number of active processes after each fork() call across the 3 loop iterations (x = 3, 2, 1).
Tracing the number of processes executing the loop body across each value of x:
- Iteration 1 (
x = 3): initial process callsfork(), resulting in processes. Both executeprintf("hello")(2 times) and decrement their copy ofxto . - Iteration 2 (
x = 2): All processes callfork(), resulting in processes. All executeprintf("hello")(4 times) and decrementxto . - Iteration 3 (
x = 1): All processes callfork(), resulting in processes. All executeprintf("hello")(8 times) and decrementxto , terminating the loop.
Total number of times printf is executed .
14
Confusing the total number of printf executions () with the final number of processes () or child processes ().
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2024 Computer Science and Information Technology - Set 1 (CS1)
- Question
- 57 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.