KERNELframe 4codeframe 5x=1frame 6free$ ./cowx=2x=1code page4 · Rdata page5 · RWcode pagedata page1pid = fork();2if (pid == 0) x = 2;3else wait(NULL);4printf("x=%d\n", x);CPU452x=121
Back: the kernel and physical memory (frames 4, 5, 6)Middle: the parent's and child's page tables, wired to their framesTokens: copied entries, a refused store, a fault and one copied pageAt the back: the kernel and physical memory, three frames. In the middle: the parent's and the child's page tables, each entry wired to the frame it points at. In front: the program, the CPU and a screen. fork copies the entries, not the pages, and makes the data page read-only in both tables. The child's write faults; the kernel copies frame 5 into frame 6 and repoints the child, and the retried store lands in frame 6. Frame numbers 4, 5 and 6 are made up for the picture: a real kernel takes whatever frames its free list hands out. A real process also has many more pages (stack, heap, libraries); the lesson shows the two that matter.

Before fork

  1. fork() must give the child its own copy of the parent's memory. Copying every page at once is slow, and often wasted: many children call exec(), which loads a new program, and throw the copy out. Copy-on-write puts off each copy until someone writes.

Sharing, not copying

The first write

Why it wins

What happens

;; step 1/10 · copy-cost
the whole program (C99, POSIX):

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int x = 1;

int main(void) {
    pid_t pid;
    pid = fork();
    if (pid == 0) x = 2;
    else wait(NULL);
    printf("x=%d\n", x);
    return 0;
}

fork()   child gets a copy of the address space
exec()   often called next: replaces it all
COW      copy a page only when it is written

Frame numbers 4, 5 and 6 are made up for the picture: a real kernel takes whatever frames its free list hands out. A real process also has many more pages (stack, heap, libraries); the lesson shows the two that matter. In a real fork the kernel copies each entry and clears its write bit in the same pass; the figure shows the copy and the write-protect as two steps. Which process runs first after fork is not fixed: here the parent's wait() makes the child print first.