Lesson 2 · Processes, threads, and CPU scheduling

fork() System Call

fork() is how a Unix process creates another: one call, two processes, and a return value that is the only way each can tell which one it is.

fork() System Call concept diagramProcess 100 calls fork. Two arrows lead from the call to the parent, still pid 100, where fork returns 101, and to the new child, pid 101, where fork returns 0. Both share the same physical pages, marked copy-on-write.pid 100calls fork()forkparent · pid 100fork() returns 101child · pid 101fork() returns 0physical pagescodedataheapstackshared, read-onlycopied on first writereturn value: −1 error · 0 in the child · child's PID in the parent
1

What Is the fork() System Call

  1. Allocate – a new PID and a new PCB for the child.
  2. Copy – registers, program counter and the address space (lazily, via copy-on-write).
  3. Duplicate – the open file-descriptor table, so both share open files.
  4. Schedule – put the child on the ready queue.
  5. Return twice – the child's PID to the parent, 0 to the child.

fork() is the POSIX system call that creates a new process. The new process, the child, is a near-exact copy of the calling process, the parent: same program, same variables, same open files, same position in the code. Both continue running from the instruction right after the call.

Inside the kernel, fork() allocates a new PID and a new process control block, copies the parent's register state, duplicates its file-descriptor table, and gives the child its own address space that starts identical to the parent's. The child is then placed on the ready queue, and from that point the two are scheduled independently.

  • The classic Unix way to create a process (vfork, clone and posix_spawn are variants)
  • Child = copy of the parent at the moment of the call
  • Both run on from the same point in the program
2

fork() Return Value

fork() is called once but returns twice, once in each process. The value is the only thing that differs between them, so every program that forks begins by branching on it.

The parent receives the child's PID because it may need it later, to wait for the child or send it a signal. The child receives 0 because it can always find its own PID with getpid() and its parent's with getppid().

What fork() returns
ValueReturned inMeaning
> 0parentsuccess; the value is the new child's PID
0childsuccess; this is the new process
−1parent (no child exists)failure, e.g. EAGAIN when the process limit is reached
  • Always test for −1 before treating the value as a PID
  • if (pid == 0) → child code; else → parent code
  • The child can call getppid() to find its parent
3

What the Child Inherits and What Differs

The child starts as a copy, but it is a separate process with its own identity. After the fork, a change to a variable in one process is invisible to the other: they share nothing in memory unless shared memory is set up explicitly.

Open files are the notable exception. The file-descriptor table is copied, but each descriptor points to the same open file description, so parent and child share a file offset. Two processes writing to one inherited file interleave their output rather than overwriting each other.

Parent and child immediately after fork()
ItemChild's copy
Code, data, heap, stackcopied (shared copy-on-write until written)
Variable valuessame values, separate storage
Open file descriptorscopied; offsets shared with the parent
Signal handlers, working directory, environmentcopied
PID and parent PIDnew PID; PPID = parent's PID
Pending signals, timers, file locksnot inherited
CPU time usedreset to 0
  • Same program and values, separate memory
  • Shared file offsets through inherited descriptors
  • New PID, fresh accounting, no pending signals
Key reference

Terms, operations, and practical uses

Core vocabulary

  • PID / PPIDA process's own identifier and its parent's.
  • exec()Replace the current program with a new one; same PID.
  • wait() / waitpid()Block until a child exits and collect its status.
  • Copy-on-writeShare pages after fork and copy one only when it is written.

Numbers to remember

  • ReturnsChild PID in the parent, 0 in the child, −1 on failure.
  • n forks in sequence2ⁿ processes, 2ⁿ − 1 of them new.
  • Zombie costOne process-table entry and one PID each.
  • Orphan's new parentPID 1, init or systemd.
Implementation

fork() traced process by process

import os


def processes_after(n):
    root = os.getpid()
    children = []
    for _ in range(n):
        pid = os.fork()
        if pid == 0:
            children = []  # a new child starts with no children of its own
        else:
            children.append(pid)
    # Each process counts itself plus every process in its children's subtrees.
    total = 1
    for child in children:
        _, status = os.waitpid(child, 0)
        total += os.waitstatus_to_exitcode(status)
    if os.getpid() != root:
        os._exit(total)
    return total


# One call, two returns. Flush first, or buffered output is copied into the
# child and printed twice.
print("before fork", flush=True)
pid = os.fork()
if pid == 0:
    print("child:  fork() returned 0", flush=True)
    os._exit(0)
os.waitpid(pid, 0)
print("parent: fork() returned the child's PID:", pid > 0, flush=True)

for n in range(1, 4):
    print(f"{n} fork() call(s) -> {processes_after(n)} processes", flush=True)

# fork + exec + wait: how a shell runs a command.
pid = os.fork()
if pid == 0:
    os.execvp("echo", ["echo", "child after exec: hello from echo"])
_, status = os.waitpid(pid, 0)
print("parent: child exited with status", os.waitstatus_to_exitcode(status))
#include <sys/wait.h>
#include <unistd.h>

#include <iostream>
#include <vector>

int processesAfter(int n) {
    pid_t root = getpid();
    std::vector<pid_t> children;
    for (int i = 0; i < n; i++) {
        pid_t pid = fork();
        if (pid == 0) {
            children.clear();  // a new child starts with no children of its own
        } else {
            children.push_back(pid);
        }
    }
    // Each process counts itself plus every process in its children's subtrees.
    int total = 1;
    for (pid_t child : children) {
        int status = 0;
        waitpid(child, &status, 0);
        total += WEXITSTATUS(status);
    }
    if (getpid() != root) _exit(total);
    return total;
}

int main() {
    // One call, two returns. Flush first, or buffered output is copied into
    // the child and printed twice.
    std::cout << "before fork" << std::endl;
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        std::cout << "child:  fork() returned 0" << std::endl;
        _exit(0);
    }
    waitpid(pid, nullptr, 0);
    std::cout << "parent: fork() returned the child's PID: " << (pid > 0 ? "True" : "False")
              << std::endl;

    for (int n = 1; n <= 3; n++) {
        std::cout << n << " fork() call(s) -> " << processesAfter(n) << " processes" << std::endl;
    }

    // fork + exec + wait: how a shell runs a command.
    pid = fork();
    if (pid == 0) {
        execlp("echo", "echo", "child after exec: hello from echo", nullptr);
        _exit(127);  // only reached if exec failed
    }
    int status = 0;
    waitpid(pid, &status, 0);
    std::cout << "parent: child exited with status " << WEXITSTATUS(status) << std::endl;
}
import java.io.IOException;

public class Main {
    // The JVM has no fork(): a child is always a whole new program, started by
    // ProcessBuilder, which uses fork + exec (or posix_spawn) underneath. So
    // this listing shows the part Java can express: spawn, then wait.
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length > 0 && args[0].equals("child")) {
            System.out.println("child:  running as a separate process");
            System.exit(3);
        }

        System.out.println("before spawn");
        String java = ProcessHandle.current().info().command().orElse("java");
        Process child = new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"), "Main", "child")
                .inheritIO()
                .start();
        int code = child.waitFor(); // the waitpid() of the Java world
        System.out.println("parent: child " + (child.pid() > 0 ? "had its own PID" : "?") + ", exit status " + code);

        Process echo = new ProcessBuilder("echo", "child after exec: hello from echo").inheritIO().start();
        System.out.println("parent: child exited with status " + echo.waitFor());
    }
}
Watch it run

Step through it

Running on pid_t a = fork(); pid_t b = fork(); printf("a=%d b=%d", a, b);

programpid_t a = fork();← 100pid_t b = fork();printf("a=%d b=%d", a, b);stdoutpid 100a = ? b = ?1 process
Step 1

One process, about to call fork()

The shell started this program as process 100. fork() is the classic way a Unix process creates another: it makes a copy of the caller, and the copy starts running at the same point.

Output
1 / 13
4

How Many Processes Does fork() Create

Because the child continues from the same point, it also executes every fork() that comes after. Each call therefore doubles the number of processes that reach the next line: n fork() calls in sequence produce 2ⁿ processes, of which 2ⁿ − 1 are new.

A printf after n forks prints 2ⁿ times. A classic trap is buffering: if text was printed without a newline before the fork, it is still sitting in the stdio buffer, and each child inherits a copy of that buffer and prints it again. Flushing before fork() avoids it.

  • n sequential forks → 2ⁿ processes
  • A fork inside if (child) only doubles that branch
  • Output order between processes is not guaranteed
  • Flush stdout before fork, or buffered text is duplicated
5

fork(), exec() and wait()

  1. fork() – the shell creates a child copy of itself.
  2. exec() – the child replaces itself with the command, e.g. ls.
  3. wait() – the parent blocks until the child exits.
  4. exit() – the child finishes; its status is handed to the parent.

fork() alone can only make more copies of the same program. To run a different program, the child calls one of the exec() family, which replaces the process's code, data and stack with a new program loaded from disk. The PID and open files stay the same, which is how a shell sets up redirections: it rearranges file descriptors in the child, then execs.

The parent usually calls wait() or waitpid(), which blocks until a child terminates and returns its exit status. A shell does exactly this for every foreground command: fork, exec in the child, wait in the parent, print the next prompt.

  • exec keeps the PID and open files, replaces everything else
  • exec returns only on failure
  • wait collects the exit status and frees the child's PCB
6

Zombie and Orphan Processes

When a process exits, its memory is freed immediately but its PCB entry is kept so the parent can read the exit status. Until the parent calls wait(), the dead process is a zombie (state Z in ps). A parent that never waits accumulates zombies, and since each holds a PID, enough of them make fork() fail.

If the parent exits first, the still-running child becomes an orphan. The kernel re-parents it to init (PID 1, systemd on modern Linux), which waits on every child it adopts, so orphans are reaped when they finish.

  • Zombie: exited child, parent has not waited
  • Orphan: running child, parent has exited
  • init adopts orphans and reaps them
  • Fix zombies by waiting, or by handling SIGCHLD
7

Copy-on-Write: Why fork() Is Fast

Copying a whole address space on every fork would be slow, and wasted when the child calls exec() straight away. Modern kernels use copy-on-write (COW): after fork, parent and child share the same physical pages, all marked read-only.

When either process writes to a shared page, the write triggers a page fault. The kernel copies just that page, gives the writer its private copy with write permission, and resumes it. Pages that are only read are never copied, so fork() costs roughly the time to copy the page tables, not the memory itself. vfork() goes further, sharing the address space outright, and is safe only when the child immediately calls exec().

  • After fork, pages are shared and read-only
  • The first write to a page copies just that page
  • fork + exec copies almost nothing
  • vfork: no copy at all, for an immediate exec