The GATE Grind

GATE 2026 CS (CS1) – Question 63

Operating System · System Calls, Processes, Threads and IPC · 2 marks · Numerical answer

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)

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 4

Explanation

Trace process creation step by step starting with parent process $P_0$:
1. At $i = 0$:
$P_0$ calls `fork()`. Child $C_1$ is created.
- In $P_0$: `fork()` returns PID of $C_1 > 0$. The condition `if (fork() == 0)` is false. $P_0$ executes `break;` and exits the loop.
- In $C_1$: `fork()` returns 0. The condition is true, so $C_1$ executes `continue;` and advances to $i = 1$.
2. At $i = 1$:
$C_1$ calls `fork()`. Child $C_2$ is created.
- In $C_1$: `fork()` returns PID of $C_2 > 0$. $C_1$ executes `break;` and exits the loop.
- In $C_2$: `fork()` returns 0. $C_2$ executes `continue;` and advances to $i = 2$.
3. At $i = 2$:
$C_2$ calls `fork()`. Child $C_3$ is created.
- In $C_2$: `fork()` returns PID of $C_3 > 0$. $C_2$ executes `break;` and exits the loop.
- In $C_3$: `fork()` returns 0. $C_3$ executes `continue;` and loop condition $i < 3$ becomes false ($i = 3$). $C_3$ exits the loop.

All 4 processes ($P_0, C_1, C_2, C_3$) reach and execute `printf("Hello!");` exactly once.
Thus, `printf` is executed 4 times.

The correct answer is 4.