11.2 Process Creation: Fork, Spawn, and Exec

OPERATING SYSTEMSSTATUS: DEVELOPINGLEVEL: INTROREVIEWED: 2026-11-18

Unix offers fork and exec as separate operations. Windows has no fork: CreateProcess starts a new program in a new process in one call, which this book calls spawn. Creating the process is not the expensive part. What differs for R is what the new process holds: a forked child inherits gigabytes of preloaded state, while a spawned one must start R and load every package again.

11.2.1 Mental model

A process is a running program. The kernel maintains an entry for each process in a table. The entry holds the process ID, the owning user, and the file descriptors. It also holds the page tables for the address space and the CPU registers for each thread. When a process exits and its parent collects the exit status, the kernel frees this entry.

Process creation starts from a running process. That process calls fork(). The kernel allocates a new entry. The new process is a child. The original is the parent. They are separate processes from that moment forward.

On Unix, fork creates a duplicate. On Windows, spawn starts a fresh program that inherits only what the parent passes on. The two paths diverge here.

11.2.2 fork

Unix fork() duplicates the calling process. The child begins with identical memory, identical registers, and copies of the parent’s file descriptors that refer to the same open files. The child resumes from the same instruction as the fork call. Both processes continue forward from that point.

Fork avoids copying memory because the kernel uses copy-on-write. The kernel copies the page tables, not the pages themselves, although copying the page tables still takes time that grows with the parent’s mapped memory. Parent and child share the same physical memory initially. When either writes to a page, a page fault occurs. The kernel copies that page and remaps the writer. Pages that neither writes remain shared.

Fork returns different values to parent and child. The parent’s fork() call returns the child’s PID. The child’s fork() call returns zero. Code can distinguish:

pid_t pid = fork();
if (pid == 0) {
  // child: pid is zero
  execve("./worker", args, env);
} else {
  // parent: pid is the child's PID
  waitpid(pid, NULL, 0);
}

The child inherits the parent’s memory, open files, signal handlers, and working directory. The child does NOT inherit the parent’s threads. If the parent is multithreaded, the child is single-threaded. Only the thread that called fork runs in the child.

That rule causes the worst hazard of fork, covered in its own section below: a child forked while another thread holds a lock inherits the lock still held, with no thread left to release it. POSIX allows such a child to call only async-signal-safe functions until it calls exec.

11.2.3 exec

The exec family (the execve system call and library wrappers such as execl and execlp) replaces the current process image with a new executable. The new executable loads. The process ID stays the same. File descriptors stay open unless they are marked close-on-exec. But the code, the heap, and the stack are all gone. They are replaced with the new executable’s code, the new executable’s heap, and a fresh stack. Exec does not return on success. Execution jumps to the new executable’s entry point.

The new program keeps the open file descriptors and any signals set to be ignored, but every signal handler is reset to the default action, because the handler’s code no longer exists. The child can read from file descriptors the parent opened. Code can set up a pipe, fork, exec a child, and communicate with the child through the pipe.

int fds[2];
pipe(fds);
if (fork() == 0) {
  dup2(fds[1], STDOUT_FILENO);  // redirect stdout to pipe write end
  close(fds[0]);                 // close read end in child
  execve("./program", args, env);
} else {
  close(fds[1]);                 // close write end in parent
  // read from fds[0]
}

The child’s stdout is the pipe. The parent reads the pipe and sees the child’s output.

11.2.4 spawn

Windows provides no fork. It provides CreateProcess. Spawn is the abstraction: fork followed immediately by exec, without returning to user code in between. Unix offers the same operation as posix_spawn. A spawned process loads a fresh executable and starts with an empty heap. It inherits little beyond what the parent passes on: with CreateProcess, that is the environment block and current directory (unless the parent supplies others), the handles the parent has marked inheritable and asks to pass, and by default the parent’s console and error mode.

Spawning a fresh Rscript process on Windows means starting from scratch. R loads from disk and every package must load again. Startup can take seconds for a heavy package stack, which is why PSOCK workers on Windows are slow to start.

Portable parallel designs cannot assume fork. Code must work on Windows, which has only spawn. The standard approach is to send the child what it needs via serialization.

11.2.5 Inheritance across fork

A Unix fork creates these inheritances:

  1. Memory contents. The entire heap is logically copied (physically shared via copy-on-write). Every variable, data frame, and function object in the parent is present in the child.

  2. Open file descriptors. Any file the parent opened, the child can read or write. Sockets, pipes, and the descriptors behind R connections are inherited too.

  3. Environment variables. PATH, HOME, and all custom variables.

  4. Signal handlers. The parent’s response to signals like SIGINT.

  5. Working directory. The child starts in the parent’s current directory.

  6. Resource limits. Process limits on stack size, open files, and CPU time.

The child does NOT inherit:

  1. Process ID. The child gets a new unique PID.

  2. Parent process ID relationships. The parent is still the parent, but if the parent dies first, the child is reparented to init (or, on Linux, to a subreaper process).

  3. Record locks. Process-associated record locks set with fcntl are not inherited, so the child must take its own. Locks taken with flock and open file description locks are inherited, because they belong to the shared open file. Mutexes behave differently: they sit in ordinary memory, so the child inherits whatever state they were in, locked ones included. That is the hazard described below.

  4. Threads. Only the thread that called fork continues in the child.

  5. Timers and pending signals. Timers set with alarm, setitimer or timer_create are not inherited, and the child starts with no pending signals.

11.2.6 The starting state of a spawned child

A spawned process starts with no copy of the parent’s memory. On Windows and Unix alike:

  1. Fresh interpreter. R starts from the executable, its globals take their startup values, and only the default packages load.

  2. Fresh heap. No objects from the parent exist.

  3. No inherited data. The child must receive input via explicit communication.

  4. Standard input/output/error. Connected to the parent or to pipes, as the parent configured.

The parent must send the child all information it needs. This happens through serialization. R objects become byte streams. The child deserializes them.

11.2.7 The hazard of fork in a multithreaded parent

If a parent has multiple threads and one of them calls fork, only that thread continues in the child. The other threads are gone. But locks held by those threads remain held.

// parent has thread A and thread B
// thread B holds lock M
// thread A calls fork
// child has only thread A, but M is locked
// child tries to acquire M
// deadlock
the deadlock is a timing accident parent process, two threads thread A thread B holds M fork 1 fork 2 child 1: M is locked nothing is left alive to unlock it child 2: M is free the child runs

A fork that lands while thread B holds M gives the child a locked M and no thread to unlock it. A fork after B releases M is safe.

The hazard is well known. R’s own help page for mcfork strongly discourages forking any R process in which a third-party library or package has started extra threads, because the child “may not be able to access resources locked in the parent” (?parallel::mcfork). Packages that start native threads (a multithreaded BLAS, OpenMP code, thread pools in compiled code) create this hazard.

A forked child of a multithreaded parent is a single-threaded process with locks held in the parent’s threads. If the child tries to acquire a lock that is held, it deadlocks.

The R ecosystem contains many packages with native threads, and a forkserver has to keep them from running in the template. sunlight’s source notes that OpenBLAS starts its thread pool as soon as the library loads, before any BLAS call. sunlight therefore starts its template with BLAS and OpenMP thread counts already set in the environment, so the template is still single-threaded when it forks, and it warns when a preloaded package has started a thread anyway, as rlang does (R/hatch.R in the sunlight source).

Spawning avoids the hazard entirely. A spawned child is a fresh process. It loads packages from scratch. It has no inherited lock state, though a library can start threads of its own as it loads, as OpenBLAS does.

11.2.8 R’s approach

GNU R evaluates R code on one thread per process. R’s parallel package offers two ways to start workers.

makeForkCluster() calls fork on Unix. The child is an R interpreter with the parent’s memory state inherited. Files open in the parent remain open in the child. Each child connects back to the parent over a socket, as PSOCK workers do. mclapply() and mcparallel() also fork, and their children send results back over pipes. Forking works on Unix-alikes only.

makePSOCKcluster() spawns fresh R processes. It works on Windows and Unix. Each spawned process loads R and necessary packages, then receives tasks.

future::plan(multicore) uses fork internally. future::plan(multisession) uses spawn. Code using multisession works on all platforms.

sunlight forks a preloaded template process. The template holds R with heavy packages such as Seurat already loaded, so a new worker skips R startup and package loading. The fork path assumes the template has only its main thread when it forks. If another thread holds a lock at that moment, a worker can deadlock.

11.2.9 Platform differences

Aspect Unix fork Windows spawn
Startup cost copy page tables, no R startup start R and load packages
Memory shared pages until written each process builds its own heap
Inheritance full memory state environment, directory, chosen handles
Threads only forking thread survives fresh process, no inherited locks
Cost of returning data serialization only serialization only

The fork path starts fast, and shares memory only until the child writes to it, which R’s garbage collector soon does. The spawn path is portable and safe. Among process-based designs, none is both fast and portable.

Further reading

  • fork(2) manual page <https://man7.org/linux/man-pages/man2/fork.2.html>.
  • execve(2) manual page <https://man7.org/linux/man-pages/man2/execve.2.html>.
  • Microsoft, Create processes <https://learn.microsoft.com/en-us/windows/win32/procthread/creating-processes>, and the CreateProcessW reference <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw>, which documents handle inheritance.
  • Butenhof, D. R. (1997). Programming with POSIX Threads <https://www.informit.com/store/programming-with-posix-threads-9780201633924>. Addison-Wesley. Chapter 6, “POSIX adjusts to threads”, covers fork in threaded programs.
  • The Open Group, fork() in POSIX.1-2024 <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fork.html>. The description and rationale cover forking a multithreaded process.

Where this appears

  • sunlight sunlight uses Unix fork so that workers inherit a template’s preloaded R session. Windows lacks fork and must spawn fresh processes.

Where to go next

Back to top