Highlights

Contents

Part III
03

Fork, exec and threads

A shell needs a way to create a child without losing its own prompt. Threads then let one process overlap work while sharing an address space. We will trace fork’s copy-on-write pages, exec’s replacement, wait’s cleanup, and the ownership choices that distinguish processes from threads.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1OS fundamentals2Processes3Fork, exec and threads4Synchronization5Deadlocks6CPU scheduling7Paging and memory8Copy-on-write9Filesystems10I/O and IPC11Protection and Linux12Complete server trace

#Section 9Fork and parent-child execution

fork() returns twice because the kernel creates a child process that continues at the instruction after the call. The parent receives the child’s PID, the child receives zero, and failure returns negative one to the caller. The two processes have separate execution state but initially similar memory mappings and inherited resource references.

Copy-on-write postpones private page copying until a write requires it. That helps a child which soon execs another image, avoiding copies of pages it would immediately discard.

FORK SHARES PHYSICAL PAGES; A WRITE CREATES ONE PRIVATE COPYFORK SHARES PHYSICAL PAGES; A WRITE CREATES ONE PRIVATE COPYparent mapchild mapphysical framespage 0page 0frame 0page 1page 1frame 1page 2page 2frame 2page 3page 3frame 3page 4page 4frame 4page 5page 5frame 5page 6page 6frame 6page 7page 7frame 7copybefore write: 32,768 B; after: 36,864 Bseven shared pages, one extra physical page
Figure 3.10Illustrative fork shares eight pages until a write creates one private copy. Orange marks the writer’s private page after the fault changes sharing.

File descriptors are inherited as references to open-file state, so parent and child can share file offsets or socket endpoints according to the kernel’s descriptor semantics. That inheritance is useful for shell pipelines and servers, but it also means a forgotten descriptor can keep a pipe from reaching end of file.

#Section 10Exec replaces the process image

exec creates no process. It replaces the calling process’s program image with a new executable, mapping its text, data, stack and shared libraries and setting a new entry point. The PID and many process relationships remain, which is why a shell can fork once, exec ls in the child and wait for that child.

The replacement discards the old user-space code and data, but descriptor inheritance follows close-on-exec rules. A descriptor marked close-on-exec does not survive, while ordinary inherited descriptors can connect the new program to a pipe or socket. The loader also validates the executable format and prepares the initial stack with arguments and environment.

EXEC REPLACES MAPPINGS WHILE KEEPING PROCESS IDENTITYEXEC REPLACES MAPPINGS WHILE KEEPING PROCESS IDENTITYold imagestack: shellheap: shelldata: shellcode: shellnew imagestack: newheap: newdata: newcode: newloaderPIDsame process identity; new entry point and address space
Figure 3.11Illustrative before-and-after address spaces. Exec replaces the program mappings and entry point while preserving the process identity; the shell parent continues separately.

The distinction matters for security and debugging. A failed exec returns to the old image, so the child must report the error and exit rather than pretending the target ran. A successful exec never returns to the old instruction stream.

#Section 11Wait, zombies and orphans

When a child exits, the kernel keeps a small termination record containing its status until the parent collects it. That retained process is a zombie. wait() or waitpid() copies the status to the parent and releases the record. A zombie is not consuming its former address space, but a large accumulation can exhaust process-table capacity.

If a parent exits while its child continues, the child becomes an orphan and is reparented to a system process or supervisor that can collect it. Orphan and zombie describe different events. An orphan may continue running normally. A zombie has already stopped and only awaits collection.

A DEAD CHILD KEEPS ITS EXIT STATUS UNTIL SOMEONE CALLS WAITA DEAD CHILD KEEPS ITS EXIT STATUS UNTIL SOMEONE CALLS WAITzombie, then reapedorphan, then adoptedparent 100child101zombie: only the recordstatus 0wait(&status)parent exitschild 202init, PID 1reparented: init willcall wait for itSIGCHLD only tells the parent; wait still has to run
Figure 3.12Illustrative trace separates exit, retained status, wait, reparenting and collection. Orange marks the wait action that releases the record.

A server should install a deliberate child-reaping path instead of assuming the shell will do it. Signals such as SIGCHLD can notify a parent, but the handler or event-loop integration must still collect all available statuses safely.

#Section 12Threads and shared process resources

A thread is an execution path inside a process. Each thread needs its own stack, registers and program counter, while threads share the process’s code, heap, globals, address space and many open resources. This sharing removes some process-creation and communication cost, but it also makes a stray write visible to sibling threads.

On common one-to-one models, the kernel schedules each thread as an execution entity and can place threads from one process on both cores. A many-to-one user-thread runtime cannot obtain the same parallelism because the kernel sees only one schedulable entity. Many-to-many models multiplex user threads over kernel entities, trading runtime complexity for flexible mapping.

PRIVATE STACKS ABOVE ONE SHARED PROCESS MAPPRIVATE STACKS ABOVE ONE SHARED PROCESS MAPone processAcalllocalsreturnprivate stack + registersBcalllocalsreturnprivate stack + registersCcalllocalsreturnprivate stack + registerscodeheapglobalsopen filesshared address space and resources
Figure 3.13Illustrative private stacks and registers sit beside shared code, heap and resource state. Orange marks the shared heap because it creates synchronization obligations.

Threads are not automatically faster. They can reduce address-space setup, but contention, cache traffic and coordination can dominate. Processes provide stronger fault isolation, while threads make low-latency shared-memory communication easy and dangerous at the same time.

Process versus thread

Separate processes isolate private address spaces. Threads share memory and descriptors, making communication easier but increasing shared-state risk; one thread’s fatal error can terminate the process.

User threads and kernel threads

A many-to-one runtime schedules several user tasks onto one kernel execution entity. It can switch those tasks cheaply, but cannot run them simultaneously on both cores without another kernel entity. One-to-one threads give the kernel a schedulable entity per thread. Many-to-many designs multiplex runtime tasks across several kernel threads. Blocking behavior depends on that mapping, so counting language tasks does not establish CPU parallelism.

HOW MANY KERNEL ENTITIES THE THREADS MAP TO DECIDES HOW MANY CORES THEY CAN USEHOW MANY KERNEL ENTITIES THE THREADS MAP TO DECIDES HOW MANY CORES THEY CAN USEmany to oneuser threadskernel entitiesK01 of 2 cores busyone to oneuser threadskernel entitiesK0K1K22 of 2 cores busymany to manyuser threadskernel entitiesK0K12 of 2 cores busya blocking call in many-to-one stalls every thread
Figure 3.14Illustrative thread mappings compare runtime work with kernel scheduling entities. Orange marks the one-to-one mapping; two physical cores still bound simultaneous execution.