What this topic covers
9 subtopics- fork()17
- Threads7
- exec() and wait()5
- Process basics5
- IPC3
- Zombies and orphans3
- Process states2
- Schedulers2
- Signals1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
"How many times does this print?" fork() puzzles are a favourite of placement tests and GATE. Each puzzle here was compiled and run on a real Unix system with terminal-style output buffering, so the counts are what you would see on screen. Around them: process states and the PCB, exec() and wait(), zombies and orphans, threads versus processes and inter-process communication.
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
In the five-state model (new, ready, running, waiting, terminated), which transition is not possible?
Show answer and explanation
Explanation
When its I/O completes, a waiting process becomes ready; only the scheduler moves a ready process to running. Running → waiting happens on an I/O request, running → ready on a timer interrupt.
Why the other options are wrong
- AHappens when the I/O completes.
- BHappens on an I/O request.
- CHappens on preemption.
How many times is x printed?
#include <stdio.h>
#include <unistd.h>
int main(void) {
if (fork() && fork())
fork();
printf("x\n");
return 0;
}
The answer is a number – work it out, then open the solution.
Show answer and explanation
Explanation
The first fork gives a parent (non-zero) and a child (0). && short-circuits in the child. The parent runs the second fork: now 3 processes. Only the original parent sees both values non-zero, so it forks once more: 4 processes.
There is no newline now. How many dashes appear on the terminal?
#include <stdio.h>
#include <unistd.h>
int main(void) {
for (int i = 0; i < 2; i++) {
fork();
printf("-");
}
return 0;
}
The answer is a number – work it out, then open the solution.
Show answer and explanation
Explanation
Without a newline the dashes stay in each process's stdio buffer, and fork() copies the buffer. After the loop there are 4 processes; each holds "--" (one dash from each iteration, inherited or its own), and flushes it at exit: 4 × 2 = 8. With "-\n" it would be 6.