fork is the POSIX system call that creates a new process by duplicating the calling process, so that two nearly identical processes continue from the same point in the code. In Linux, fork is the traditional foundation of process creation: shells, daemons and servers use it to start every new program, usually followed by a call from the exec family that replaces the copied program with a different one.
The defining property of fork is that it is called once but returns twice. The parent receives the process ID of the child, the child receives 0, and a failure returns -1 with no child created. This single return-value test is how every forked program decides which role it plays.
How the fork system call duplicates a process
When a process calls fork, the kernel builds a new task structure for the child and gives it a fresh process ID, while copying or sharing almost everything else from the parent. The child inherits the virtual address space, open file descriptors, signal handlers, current working directory, environment, resource limits and credentials. Both processes then resume execution at the instruction immediately after the call.
Modern Linux does not physically copy the parent’s memory. Instead it uses copy-on-write (COW): parent and child share the same physical pages, which the kernel marks read-only in both page tables. Only when either process writes to a page does a page fault trigger a private copy of that single page. This makes fork fast even for large processes, because the main cost is duplicating page tables, not data.
Internally, the glibc fork() wrapper on Linux invokes the clone() system call with flags that request a full, separate copy of resources. The same kernel path, kernel_clone(), serves fork, vfork and thread creation, which differ only in which resources are shared.
The following table shows what the child inherits and what is reset or made unique.
| Attribute | State in the child | Practical consequence |
|---|---|---|
| Process ID | New unique PID | Parent identifies the child by this value |
| Parent process ID | Set to the caller’s PID | Child appears under the parent in the process tree |
| Memory pages | Shared copy-on-write | Writes by one side stay invisible to the other |
| File descriptors | Duplicated, sharing open file descriptions | File offsets and status flags are shared |
| Signal handlers | Inherited | Same handling until exec resets them |
| Pending signals | Cleared | Child starts without queued signals |
| Threads | Only the calling thread | Other threads do not exist in the child |
| Record locks (fcntl) | Not inherited | Child must acquire its own locks |
| Timers and resource usage | Reset | CPU time counters start at zero |
Return values and the fork-exec-wait pattern
Every correct use of fork branches on the return value immediately after the call. A typical shell runs the sequence fork(), then execve() in the child to load the new program, while the parent calls waitpid() to collect the child’s exit status. This trio is known as the fork-exec-wait pattern and underlies nearly all command execution on Unix-like systems.
Each return value has a fixed meaning that the program must handle explicitly.
| Return value | Received by | Meaning | Typical action |
|---|---|---|---|
| Positive PID | Parent | Child created successfully | Store PID, later call waitpid |
| 0 | Child | Code now runs in the new process | Set up redirections, call exec |
| -1 | Parent only | No child created, errno set | Report EAGAIN or ENOMEM, retry or exit |
Separating fork from exec is a deliberate design choice. Between the two calls, the child can rearrange file descriptors, change directory, drop privileges or adjust limits with plain code, which is how shells implement pipes and redirection without any special kernel interface.
If the parent never calls wait() or waitpid(), a terminated child remains a zombie process, holding its process table entry until it is reaped. If the parent exits first, the child is reparented to init (PID 1) or to a designated subreaper, which reaps it.
fork compared with vfork, clone and posix_spawn
Linux offers several process creation interfaces, and fork is the most general but not always the most efficient. The right choice depends on whether the child will run its own code or immediately execute another program, and on how much state should be shared.
| Call | Memory handling | Parent behavior | Best use |
|---|---|---|---|
| fork | Separate address space, copy-on-write | Continues immediately | Child runs its own logic |
| vfork | Child borrows parent memory | Suspended until exec or _exit | Legacy fast spawn, risky |
| clone | Configurable with flags | Depends on flags | Threads, containers, namespaces |
| clone3 | Configurable, extensible struct | Depends on flags | New code needing pidfd or cgroup placement |
| posix_spawn | Library chooses efficient path | Continues immediately | Launching another program |
Threads are created with clone() and the CLONE_VM flag, so they share one address space, whereas fork deliberately does not. Container runtimes use clone flags such as CLONE_NEWPID to place the child in a new Linux namespace, and clone3() can start the child directly inside a chosen cgroup.
Performance and resource limits of fork
Although copy-on-write avoids copying data, fork still scales with the size of the address space. Duplicating page tables for a process with tens of gigabytes of mapped memory can take milliseconds rather than microseconds, and the subsequent page faults add latency when either side writes. Databases such as Redis, which fork to write snapshots, show memory growth proportional to the pages modified during the snapshot.
Fork can fail for several resource reasons, and each one points to a different administrative control.
| Symptom | Likely cause | Remedy |
|---|---|---|
| EAGAIN | Per-user process limit reached (RLIMIT_NPROC) | Raise the limit with ulimit -u or limits.conf |
| EAGAIN in a container | cgroup pids.max reached | Increase the cgroup pids limit |
| ENOMEM | Strict overcommit cannot reserve memory | Review vm.overcommit_memory or use posix_spawn |
| System-wide failure | kernel.pid_max or threads-max exhausted | Find runaway processes, adjust sysctl |
| OOM kills after fork | COW copies exceeded available RAM | Reduce writes during child lifetime |
A fork bomb is a program that forks repeatedly until the process table is full, which can make a system unresponsive. The standard defenses are a per-user RLIMIT_NPROC set through ulimit and a pids controller limit in cgroups, which systemd applies to user sessions by default.
Pitfalls when using fork
Most bugs involving fork come from inherited state that the programmer did not expect to be duplicated. Experienced developers treat the interval between fork and exec in a multithreaded program as especially dangerous.
- Forking multithreaded programs: only the calling thread survives, so a mutex held by another thread stays locked forever; POSIX permits only async-signal-safe functions in the child before exec.
- Duplicated stdio buffers: unflushed
printfoutput is copied and printed twice unless buffers are flushed before fork. - Leaked file descriptors: descriptors without the close-on-exec flag (
O_CLOEXEC) remain open in the executed program. - Shared file offsets: parent and child writing to the same descriptor interleave output because the offset is shared.
- Unreaped children: ignoring child exit creates zombie processes; install a SIGCHLD handler or call waitpid.
- Randomness and secrets: a cloned random number generator state can produce identical values in parent and child unless reseeded.
In plain words
Calling fork is like asking a photocopier to copy a person who is halfway through a task. Afterward there are two of them, standing at exactly the same step, with the same notes and the same tools. The only difference is a name tag: the original learns the new copy’s number, and the copy is told it is the copy.
From that moment, the two work independently. Usually the copy throws away the old task and starts a completely different job, which is what happens every time a command runs in a terminal. The key idea is simple: fork makes a twin, and the twin then decides what to become.
A real-world example
A system administrator types grep error /var/log/syslog | wc -l into Bash on a Linux server. Bash first creates a pipe, then calls fork twice. In the first child it connects standard output to the pipe and executes grep; in the second child it connects standard input to the pipe and executes wc. The parent shell closes its own pipe ends and calls waitpid for both children.
The whole operation takes a few milliseconds, and the administrator sees a single number. Later, a build job on the same server fails with “Resource temporarily unavailable”. The administrator checks ulimit -u, finds a limit of 4,096 processes for the build user, and sees that a misconfigured test spawned thousands of workers. After fixing the test and setting a cgroup pids limit of 2,048 for the build service, fork failures stop and the rest of the server stays responsive.