GATE CS 2024 Set 1 — Question 57

NAT+2 / -0HardProcess Creation (fork, exec)Processes & ThreadsOperating System

Operating System → Processes & Threads → Process Creation (fork, exec)

Last updated

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 _______

Correct answer

14 to 14

Solution

In each iteration of the while loop, the fork() system call is executed, which doubles the number of processes. After the fork, both the parent and the child process execute the printf("hello") statement.
Let NiN_i be the number of processes at the start of iteration ii.
  • Iteration 1 (x=3x=3): N1=1N_1 = 1. After fork(), there are 2×1=22 \times 1 = 2 processes. Both print "hello". Total prints in this iteration = 22.
  • Iteration 2 (x=2x=2): N2=2N_2 = 2. After fork(), there are 2×2=42 \times 2 = 4 processes. All 44 print "hello". Total prints in this iteration = 44.
  • Iteration 3 (x=1x=1): N3=4N_3 = 4. After fork(), there are 2×4=82 \times 4 = 8 processes. All 88 print "hello". Total prints in this iteration = 88.
After the third iteration, xx becomes 00 and the loop terminates for all processes.
Total number of times printf is executed = 2+4+8=142 + 4 + 8 = 14.
Note: The wait(NULL) call in the child process returns immediately (as it has no children), while in the parent process, it waits for the child to finish. This affects the order of execution but does not change the total count of printf calls.

More questions on Processes & Threads

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free