Processes & the Process Abstraction

fork

/ fork /

Imagine a photocopier that, on one press, produces a near-perfect duplicate of a worker mid-task, with the same notes, the same place in the to-do list, the same open folders. Now there are two workers who can go on independently. On Unix-like systems, fork is the system call that creates a new process by duplicating the calling process: the new child is a copy of the parent, and from then on the two run separately.

When a process calls fork(), the OS creates a child process that is almost an exact copy of the parent: the same program code, a copy of the parent's memory (heap, stack, data), the same open files, and the same point of execution. The single call returns twice, once in each process: in the parent it returns the child's PID (a positive number), and in the child it returns 0, which is how each piece of code can tell which process it is and branch accordingly. To avoid copying all the parent's memory immediately, real systems use copy-on-write: parent and child initially share the same physical pages marked read-only, and a page is only truly copied when one of them writes to it.

Fork is the classic Unix way to create processes, and it is almost always paired with exec: the child forks (making a copy of the parent) and then immediately calls exec to replace itself with a different program. That two-step (fork then exec) is how a shell launches a command. A common surprise for beginners: after fork, parent and child have separate memory, so a variable the child changes does not change in the parent. They started identical, but they are now two independent processes that no longer share their writable memory.

pid = fork(); if (pid == 0) { /* child code */ } else { /* parent code, pid is the child's PID */ }. The same line of code runs in two processes, each taking a different branch.

One call, two returns: 0 in the child, the child's PID in the parent.

After fork, parent and child have separate memory (copy-on-write under the hood). Changing a variable in one does not change it in the other; they are independent processes.

Also called
fork()process cloning複製行程分叉