GATE / CS ARCHIVE

GATE CSE 2026 SET 1 / QUESTION 63

A fork loop with one continuing child

Operating Systems · Processes, Threads & System Calls · Full GATE CSE 2026 Set 1 paper

GATE 2026 Set 1, Q63 2 marks · NAT
Report issue

Processes, Threads & System Calls

Question 63, GATE 2026: In main, for i=0; i<3; i++, the program calls fork(). The child (fork()==0) executes continue; the parent executes break. After the loop each process executes printf("Hello!"). All forks succeed. Count executions of printf.
Tap to enlarge
Answer & solution

Official answer: 4

Step through it (9 steps)

Givens and goal

In main, for i=0; i<3; i++, the program calls fork(). The child (fork()==0) executes continue; the parent executes break. After the loop each process executes printf("Hello!"). All forks succeed. Count executions of printf.

Approach

Trace which process continues the loop after each fork rather than assuming every process performs all three iterations.

Step-by-step solution

1. Begin with process P0 at i=0. It forks child P1. P0 receives a nonzero return value, skips the child branch, executes break, and prints once.
2. P1 receives zero and executes continue. In a for loop, continue proceeds to the increment i++, then tests the condition. Thus P1 reaches i=1 and forks P2. P1 then breaks and prints once; P2 continues.
3. P2 reaches i=2 and forks P3. P2 breaks and prints once. P3 continues to the increment, giving i=3, where i<3 is false. P3 exits the loop normally and prints once.
4. The process structure is a chain P0→P1→P2→P3, with exactly three successful forks and four processes. Every one reaches the single printf once, so the answer is 4.
5. The execution order of the four prints is scheduling-dependent, but the count is not. The usual 2^3=8 doubling applies only when both parent and child continue forking on later iterations; here each parent immediately leaves the loop. There is also no pre-fork buffered print in the snippet whose output could be duplicated.

Original paper, page 46 · Answer key