GATE / CS ARCHIVE

GATE CSE 2024 SET 1 / QUESTION 57

Count forked executions

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

GATE 2024 Set 1, Q57 2 marks · NAT
Report issue

Processes, Threads & System Calls

Question 57, GATE 2024: The code is int x=3; while(x>0){fork(); printf("hello"); wait(NULL); x--;}. The printed question assumes successful system calls and asks how many times printf executes. The ordinary POSIX behavior of wait creates a qualification to that premise.
Tap to enlarge
Answer & solution

Official answer: 14

Step through it (24 steps)

Approach: Count statement executions in the process tree, not the number of visible copies of buffered output or the number of processes at one instant.
1. At x=3, the original process forks into a parent and child. Both continue after fork and execute printf, giving 2 executions associated with that loop value.
2. Each process has its own copied x. Both eventually reach x=2, and each forks again, giving 4 printf executions at that level. At x=1, the four process lineages each fork, giving 8 more executions.
3. Total executions are 2+4+8=14. wait may delay a parent while descendants finish, so these levels need not occur simultaneously, but waiting does not erase the later iterations of the parent's loop.
A newly created child initially has no child of its own. Its first wait(NULL) therefore returns −1 with ECHILD on POSIX, contradicting the blanket premise that all calls succeed. The code ignores the return value, so the intended count is still 14 when normal no-child wait failures are allowed. Buffered “hello” text can also be copied by fork; that concerns output rendering, not the number of printf executions asked here.
Answer: 14 under the intended counting model. Existing discrepancy CS-2024-S1-Q57-WAIT-PREMISE remains preserved.

Original paper, page 34 · Answer key