fork() System Call Explained: Return Values, Process Counts and Worked Traces

A practical fork() lesson that follows values and return paths across six processes, then fixes the counting, scheduling, buffering, wait and exec traps.

KnowledgeGate Team

Exam prep & CS education

Updated 27 Nov 20266 min read
fork() System Call Explained: Return Values, Process Counts and Worked Traces

fork() looks like one ordinary function call, yet after it succeeds, two processes continue from the next statement. That makes return-value branches, process counts and printed-output questions easy to misread. The program progresses from a single process to six, carrying x from 2 to the output multiset {3, 14, 4, 4, 15, 15}. Process labels and PIDs below are illustrative, and every count assumes successful calls unless failure is discussed. Place the mechanism within the broader GATE CS exam preparation route when revising operating systems.

Read one fork() as two returns from one call

A successful fork() creates a child, and both processes resume after the call. Suppose P0, PID 4100, runs pid_t a = fork() and creates PID 4101. P0 sees a = 4101, the child's positive PID; the child sees a = 0. Their getpid() results are 4100 and 4101, so a is not the parent's PID. On failure, the caller gets -1 and no child exists.

c
if (a == 0) { /* child */ }
else if (a > 0) { /* parent */ }
else { /* failure */ }

Creation does not decide scheduling. Either process may run next, so source order cannot establish cross-process print order.

Know what starts equal, becomes independent and remains shared

Parent and child start with equal logical memory but separate address spaces. Changing the parent's x from 5 to 8 leaves the child's copy at 5. Linux commonly uses copy-on-write: pages may initially share physical storage, then a write gives the writer a private copy. This optimisation does not make ordinary variables shared.

POSIX says inherited descriptors can share an open file description and offset. From offset 0, let the child write AB and exit; the parent waits, then writes CD. The shared offset moves 0 -> 2 -> 4, producing ABCD. Waiting removes the ordering race.

A C output buffer is user-space memory and can be duplicated. If printf("KG") stays unflushed before two unconditional successful forks and all processes exit normally, KG can flush four times. Buffering mode matters. fflush(stdout) before the first fork makes the pre-fork text appear once.

Work the six-process trace step by step

Assume all three call sites in this fragment succeed:

c
int x = 2;
pid_t a = fork();
if (a == 0) x += 3;
else x *= 2;

pid_t b = fork();
if (b == 0) x += 10;
else x -= 1;

if (a == 0) fork();
printf("%d\n", x);

P0 takes the first parent path: 2 * 2 = 4. At b, it gets 4 - 1 = 3, while child P2 gets 4 + 10 = 14. First child P1 starts with 2 + 3 = 5; at b, it gets 5 - 1 = 4, while P3 gets 5 + 10 = 15. Both retain a == 0, so the last call creates P4 and P5 without changing x.

Process

Created by

inherited a-branch

b-branch

final conditional fork?

printed x

P0

Original

Parent: 2 * 2 = 4

Parent: 4 - 1 = 3

No

3

P2

P0 at b

a > 0, x = 4

Child: 4 + 10 = 14

No

14

P1

P0 at a

Child: 2 + 3 = 5

Parent: 5 - 1 = 4

Creates P4

4

P4

P1 at final call

a == 0, x = 4

Inherits parent path

Born here

4

P3

P1 at b

a == 0, x = 5

Child: 5 + 10 = 15

Creates P5

15

P5

P3 at final call

a == 0, x = 15

Inherits child path

Born here

15

The six outputs form multiset {3, 14, 4, 4, 15, 15}. Their line order is unspecified.

Process tree for the three-fork trace, showing how x reaches 3, 14, 4, 4, 15 and 15 across six processes.

Count processes without blindly applying 2^n

When every process executes n unconditional successful calls, totals are 2^n, with 2^n - 1 children. Three calls give 1 -> 2 -> 4 -> 8: eight processes, seven children. Our trace has four after two calls, but only two a == 0 paths call again, so 4 + 2 = 6.

For fork() && fork(), the first parent evaluates the second call, giving two leaves; the first child skips it, giving one. Total: 2 + 1 = 3. For fork() || fork(), the parent skips to one leaf; the child calls again and gives two. Total: 1 + 2 = 3. Straight-line calls give four. Use fork() Questions in GATE for the canonical straight-line, loop, short-circuit and output-buffer drills. The calculations here connect those rules to a larger state ledger that preserves a and b while x diverges across six paths.

These counts assume success. In C, -1 is truthy but creates no child.

Short-circuit fork trees: three processes for fork() && fork(), three for fork() || fork(), and four for two plain calls.

Trace wait() and exec() without confusing their jobs

fork() creates a process. Successful exec replaces the caller's program image without creating one. wait() and waitpid() synchronise with a child and collect its status; they do not merge processes or reverse the fork.

PID 4100 forks child 4101, which calls _exit(7). The parent runs waitpid(4101, &status, 0) and, after a successful return and normal-exit checks, obtains 7. Only then can it safely print child 4101 exited 7.

If 4101 successfully calls exec, it remains PID 4101. No seventh process appears without another fork.

Handle the traps that change an otherwise correct answer

Repair these six mistakes:

  • Children versus total processes -> say whether the original is included.

  • Every written call doubles the count -> mark which paths reach it.

  • Parent prints first -> give a multiset unless synchronisation fixes order.

  • Variables are shared -> copy values at each split and update separately.

  • Parent's positive return is its PID -> label it child PID.

  • Failure cannot happen -> assume success explicitly or trace -1.

In a multi-threaded process, POSIX says the child initially replicates only the calling thread. Inherited synchronisation state can be delicate, so production code often keeps the child on a restricted path towards exec. That is not a blanket claim that every multi-threaded use is unsafe.

In the six-process trace, P2 skips the last call because it inherited a > 0; P4 prints 4 because it copied P1's private value. First learn the process-versus-thread ownership table, copy-on-write page arithmetic and the canonical 1 -> 2 -> 4 -> 6 tree in Threads and Process Creation in OS: fork() Worked Examples. Then re-derive this return-state trace, whose a and b branches produce six distinct path histories and four distinct printed values.

Threads and Process Creation in Operating Systems: fork(), Thread Models and Worked Examples extends path counting with a 1 -> 2 -> 3 -> 6 PID ledger and user-to-kernel thread mappings. Return-state questions add a different burden: preserve each earlier fork() result while memory values, file offsets and output buffers follow their own inheritance rules.

How exams can test the fork system call

Practice commonly asks for totals or children, a process tree, an output multiset, return paths, short-circuit counts, fork versus exec, or buffering and file-offset traps. This is not an official paper pattern.

Use this 20-second routine:

  1. Mark the success assumption.

  2. Start at one; split only paths reaching the call.

  3. Copy local values and preserve returns such as a.

  4. List leaves, then answer exactly what was asked.

Answer from control flow and process semantics, not from an assumed marks split or topic weightage. The trace routine remains the same whether a question asks for total processes, children, output lines or final variable values.

Short version and the next study step

Remember five invariants: both processes resume after success; the child sees 0, while the parent sees the child PID; memory updates are local; scheduling is not source order; and counts double only when every process reaches the call. Re-derive the worked trace by writing a, b and x on every branch before counting leaves.

Use the GATE Test Series for broader practice after the branch ledger is reliable.