fork · system call

Also known as: fork system call

On this page 7

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.

AttributeState in the childPractical consequence
Process IDNew unique PIDParent identifies the child by this value
Parent process IDSet to the caller’s PIDChild appears under the parent in the process tree
Memory pagesShared copy-on-writeWrites by one side stay invisible to the other
File descriptorsDuplicated, sharing open file descriptionsFile offsets and status flags are shared
Signal handlersInheritedSame handling until exec resets them
Pending signalsClearedChild starts without queued signals
ThreadsOnly the calling threadOther threads do not exist in the child
Record locks (fcntl)Not inheritedChild must acquire its own locks
Timers and resource usageResetCPU time counters start at zero
Process attributes after fork

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 valueReceived byMeaningTypical action
Positive PIDParentChild created successfullyStore PID, later call waitpid
0ChildCode now runs in the new processSet up redirections, call exec
-1Parent onlyNo child created, errno setReport EAGAIN or ENOMEM, retry or exit
Meaning of fork return values

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.

CallMemory handlingParent behaviorBest use
forkSeparate address space, copy-on-writeContinues immediatelyChild runs its own logic
vforkChild borrows parent memorySuspended until exec or _exitLegacy fast spawn, risky
cloneConfigurable with flagsDepends on flagsThreads, containers, namespaces
clone3Configurable, extensible structDepends on flagsNew code needing pidfd or cgroup placement
posix_spawnLibrary chooses efficient pathContinues immediatelyLaunching another program
Process creation calls in Linux

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.

SymptomLikely causeRemedy
EAGAINPer-user process limit reached (RLIMIT_NPROC)Raise the limit with ulimit -u or limits.conf
EAGAIN in a containercgroup pids.max reachedIncrease the cgroup pids limit
ENOMEMStrict overcommit cannot reserve memoryReview vm.overcommit_memory or use posix_spawn
System-wide failurekernel.pid_max or threads-max exhaustedFind runaway processes, adjust sysctl
OOM kills after forkCOW copies exceeded available RAMReduce writes during child lifetime
Common fork failures and their causes

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 printf output 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.