Course contentsShow
← C
Lesson 1075 of 1,21915. Systems ProgrammingFree lesson

Process duplication and copy-on-write

Process duplication and copy-on-write

What you'll learn: How the fork() system call creates a new process efficiently by sharing memory until it is actually needed.

The Clone Command

In systems programming, the primary way to create a new process is by using the fork() system call. When a program calls fork(), the operating system creates an exact duplicate of the calling process. This new process (the child) gets a copy of the original process's (the parent) variables, file descriptors, and code.

Imagine you are writing in a notebook and decide you want a friend to continue the work on a separate page. fork() is like a magical photocopier that instantly produces an identical notebook for your friend, starting from the exact line where you left off.

The Efficiency Problem

If a process is using 1GB of RAM, copying all that data immediately would be incredibly slow and wasteful. This is especially true because, in many cases, the child process immediately calls exec() to start a completely different program, throwing away all that copied data.

To solve this, Linux and Unix systems use a clever optimization called Copy-on-Write (COW).

How Copy-on-Write Works

Instead of physically copying the memory, the OS gives the child process a set of pointers that look at the same physical memory as the parent. Both processes treat this memory as "read-only."

As long as both processes are just reading variables, they share the same physical RAM. The actual "copying" only happens the moment one of the processes tries to write to or modify a piece of memory. At that precise second, the OS intercepts the write, creates a real copy of just that specific page of memory for the process that wants to change it, and then lets the write proceed.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
    int secret_number = 42;

    pid_t pid = fork();

    if (pid == 0) {
        // I am the child. 
        // Initially, I share 'secret_number' with my parent via COW.
        // The moment I change it, a private copy is made for me.
        secret_number = 100; 
        printf("Child secret: %d\n", secret_number);
    } else {
        // I am the parent.
        sleep(1); // Wait for child to finish
        printf("Parent secret: %d\n", secret_number);
    }

    return 0;
}

In the code above, secret_number is shared until the child modifies it. The parent's version remains 42 because the OS performed a "Copy-on-Write" the moment the child assigned 100 to the variable.

Key takeaway

fork() creates a twin process, but Copy-on-Write ensures that memory is only physically duplicated when one process tries to modify it.