Free — no signup required

The Lifecycle Part 1: Birth by Cloning (`fork`)

2 min read

The Universal Parent

In Linux, new processes are not conjured from nothing — they are cloned from an existing process. This is one of the most elegant and counterintuitive design decisions in Unix.

Every process on your system (except PID 1) was created by an existing parent process using a system call named fork(). When a running process calls fork(), the operating system creates an almost exact duplicate of that process at that precise moment in time.

  • The original process is called the Parent.
  • The new duplicate is called the Child.
  • The child receives a new, unique PID.
  • Both processes resume execution from the exact same point in the code — the line right after fork() returned.

How do the parent and child know which one they are? fork() returns different values to each: it returns 0 to the child, and the child's new PID to the parent. This single return-value difference is how a program branches its behavior after forking.

pid_t pid = fork();

if (pid == 0) {
    // We are the child process
    printf("I am the child, my PID is %d\n", getpid());
} else {
    // We are the parent process
    printf("I am the parent, my child's PID is %d\n", pid);
}

Copy-on-Write (CoW): Naively, cloning a process would mean copying all of its memory immediately — potentially gigabytes of RAM. Linux avoids this with Copy-on-Write. After fork(), the parent and child share the same physical memory pages, marked read-only. Only when one of them tries to write to a page does the kernel make a private copy of that page for the writer. This makes fork() extremely fast regardless of process size, because most forked children immediately call exec() (see next section) before they ever write to memory.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free