KERNELPID 100runningPID 101/bin/echo$ ./a.outhiexit 0KERNEL SIDEKERNEL SIDE1pid = fork();2if (pid == 0)3 execvp("echo", argv);4waitpid(pid, &status, 0);1pid = fork();2if (pid == 0)3 execvp("echo", argv);4waitpid(pid, &status, 0);/bin/echo hipidstatuspidstatus1010hi0
Back: the kernel's side (kernel, process table, disk, screen)Front: the parent process and, once forked, the childTokens: system calls, the copy, return values and the exit statusThe kernel's side at the back: the kernel, the process table with one PCB per process, the disk and the screen. The user's side in front: the parent's code and memory, and the place where the child appears. fork copies the parent into a new process 101 and returns 101 to the parent and 0 to the child. waitpid blocks the parent. exec turns the child into /bin/echo with the same PID. echo prints hi and exits, leaving a zombie PCB that wait collects. After fork, either process may run first: the scheduler decides. Here the parent runs first and blocks in waitpid(). If the child ran first and had already exited, waitpid() would find the zombie and return at once. The result is the same.

The process table

  1. A running program can start another with three system calls. fork() copies the calling process. exec() swaps the program inside a process for a new one. wait() lets the first process collect the result. Each is work the kernel does.

fork: copy

wait: block

exec: replace

wait: collect

What happens

;; step 1/11 · three-calls
fork()   copy me: a new process, the child
exec()   replace my program with another one
wait()   sleep until my child ends, then get its result

the whole program (C99, POSIX):

#define _POSIX_C_SOURCE 200809L  /* fork, execvp, waitpid under -std=c99 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    char *argv[] = {"echo", "hi", NULL};
    pid_t pid;
    int status;
    pid = fork();
    if (pid == 0)
        execvp("echo", argv);
    waitpid(pid, &status, 0);
    if (pid == 0) return 127;   /* only if exec failed */
    printf("exit %d\n", WEXITSTATUS(status));
    return 0;
}

Copying a whole memory would be slow, so Linux uses copy-on-write: after fork both processes share the same pages, marked read-only, and a page is copied only when one of them writes to it. The lesson draws the copy as if it were made at once. The PIDs 100 and 101 are made up for the example. Linux hands out the next free number, counting up from the last one used and wrapping around at pid_max, so real PIDs depend on what else has run.