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 ________. (answer in integer)
Official answer and solution
- Official answer
- 4
- From
- Official GATE 2026 answer key
Solution
Trace the control flow of parent (fork() != 0, which hits break) versus child (fork() == 0, which hits continue) in each loop iteration.
In each iteration :
- The calling (parent) process receives a non-zero PID from
fork(), skips theifbody, executesbreak;, exits theforloop immediately, and executesprintf("Hello!");. - The newly created child process receives
0fromfork(), executescontinue;, and advances to the next iteration of the loop.
Thus:
- : Initial process spawns child and breaks out of the loop.
- : spawns child and breaks out of the loop.
- : spawns child and breaks out of the loop; increments to and terminates the loop normally.
All processes () execute printf("Hello!"); once, for a total of 4 times.
4
Assuming processes are created by overlooking the break; statement executed by the parent.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2026 Computer Science and Information Technology - Session 1 (CS1)
- Question
- 63 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.