Skip to main content

Linux Process Management: Fork, Exec, and Beyond

Master Linux process management through interactive visualizations. Understand process lifecycle, fork/exec operations, zombies, orphans, and CPU scheduling.

The Heart of Linux: Process Management

Every program you run on Linux becomes a process - a living entity with its own memory space, resources, and lifecycle. From the moment you boot your system with PID 1 (init/systemd) to the thousands of processes running right now, understanding process management is key to mastering Linux.

Think of it this way

  • Processes are like actors on a stage
  • The kernel is the director
  • CPU cores are the stages where actors perform
  • The scheduler decides who performs when

Watch every step of process creation, execution, and termination - from fork to zombie reaping. Pick a scenario, then step through it or press Play:

The Process Tree

Every process on a Linux system is part of a hierarchical tree structure. PID 1 (systemd/init) sits at the root as the ancestor of all processes. Click any process to explore its relationships: its ancestors and descendants are highlighted, Fork creates a child, and Kill terminates it and re-parents its children to init:

Process tree
View

SelectedAncestors (parent chain)Descendants (children)

Process Fundamentals

What is a Process?

A process is more than just a running program. It's a container managed by the kernel that includes:

  • Identity: PID (Process ID), PPID (Parent PID), UID/GID (owner)
  • State: RUNNING, READY, WAITING, STOPPED, ZOMBIE
  • Memory: Code, data, heap, stack (separate virtual address space)
  • Resources: Open files, network connections, signals
  • Scheduling: Priority, nice value, CPU time consumed

The kernel represents each process with a task_struct - a data structure containing all this metadata (about 10KB per process).

Process vs Thread

AspectProcessThread
WeightHeavy-weightLight-weight
MemorySeparate address spaceShared within process
Creationfork() (slower)clone() (faster)
CommunicationIPC requiredDirect memory access

When Firefox runs with 47 threads, they all share memory and file descriptors but have separate stacks and registers.

The Fork-Exec Model

Analogy: the photocopier

  • fork() = Photocopying yourself. You now have two identical copies, both thinking they're the original.
  • exec() = The photocopy transforms into a completely different document. Same piece of paper (PID), but entirely different content.

fork(): Cloning Processes

fork() creates a new process by duplicating the calling process:

  1. Kernel creates child: New PID, copy of task_struct
  2. Copy-on-Write (COW): Memory pages shared, not copied immediately
  3. Returns twice: Returns 0 to child, child PID to parent
  4. Identical but separate: Same code position, but two different processes

exec(): Transformation

exec() replaces the current process image with a new program:

  1. Same PID: Process identity preserved
  2. New program: Code, data, stack replaced from executable file
  3. File descriptors preserved: Open files remain open (unless close-on-exec)
  4. Common pattern: fork() followed by exec() in child

Copy-on-Write Deep Dive

Step through a fork and an exec to see which memory pages the parent and the child share copy-on-write, and when a page is really copied. Memory pages are shared until modified:

fork(), exec() and copy-on-write
Step 1 / 6
Parent Process Running

Parent process (bash) is running with its own memory space. Each region occupies physical pages.

Parent
1234bashRUNNING
main+0x42
Code
4 pages · active
Data
2 pages · active
Heap
8 pages · active
Stack
1 pages · active
Child
No child process yet
Virtual pages
15
Physical pages
15
Shared, copy-on-writeCopied or newly loadedBeing released

Parent owns all 15 physical pages exclusively. About to call fork()...

Process States

Every process is always in one of these states. Click a state or a transition to explore it, or press Play to move one process through its lifecycle:

Process states
Step 1 / 10
Transitions
Event log
  1. Press Play to run the process through its lifecycle.

A process spends most of its time in READY (waiting for CPU) or WAITING (blocked on I/O). The ZOMBIE state is special - the process is dead but must exist until parent retrieves its exit status.

State Transitions Summary

FromToTrigger
NEWREADYfork() completes
READYRUNNINGScheduler dispatch
RUNNINGREADYTime slice expired
RUNNINGWAITINGI/O, sleep, lock
WAITINGREADYI/O complete, wake
RUNNINGSTOPPEDSIGSTOP received
STOPPEDREADYSIGCONT received
RUNNINGZOMBIEexit() called

Zombies & Orphans

Analogy: family affairs

  • Zombie = A tombstone waiting for someone to read it. The person is gone, but the marker remains until the family (parent) acknowledges it.
  • Orphan = A child whose parent died. Automatically adopted by the state (init/systemd) to ensure proper care.

Zombie Processes

When a process terminates, it becomes a zombie - dead but not fully gone:

  • Why exist? Must preserve exit status for parent to retrieve
  • What's left? Only task_struct (process descriptor), no memory
  • How to see? ps aux | grep defunct or state shows 'Z'
  • How to kill? You can't! Already dead. Parent must call wait()
  • Problem: If parent never calls wait(), zombie persists forever

Orphan Processes

When a parent dies before its children:

  • Kernel re-parents: Orphans automatically adopted by init (PID 1)
  • init reaps: init periodically calls wait() to clean up orphans
  • No zombie accumulation: init ensures orphans don't become permanent zombies

This is why PID 1 (init/systemd) is special - it's the ultimate parent that never dies and always cleans up.

The simulator steps through both cases: a parent that dies while its child is still running, and a child that exits while its parent never calls wait():

Orphans and zombies
Scenario
Step 1 / 5
2s
Normal Operation

Parent (PID 1000) and child (PID 1001) are both running happily.

  • 1systemd
    PPID 0
    RUNNING
  • 1000parent
    PPID 1
    RUNNING
  • 1001child
    PPID 1000
    RUNNING

Sessions and Process Groups

Analogy: office organization

  • Session = An office floor containing multiple teams
  • Process Group = A team that receives group messages (signals) together
  • When you press Ctrl+C, the memo goes to the foreground team only!

Signal Delivery

Understanding why Ctrl+C kills an entire pipeline but leaves background jobs alone: signals are delivered to all processes in the foreground process group. Send a signal, or move another job to the foreground first:

Signals and process groups
Send
Session 1000/dev/pts/0
Shell
PGID 1000 · Background
  • 1000bash
    RUNNINGleader
    handler: ignored
Pipeline
PGID 1010 · Foreground
  • 1010cat
    RUNNINGleader
    handler: default
  • 1011grep
    RUNNING
    handler: default
  • 1012wc
    RUNNING
    handler: default
Background Job
PGID 1020 · Background
  • 1020sleep
    RUNNINGleader
    handler: default
Terminal Output
$ cat file.txt | grep pattern | wc -l
# Pipeline started as foreground job

The Hierarchy

  • Session: A collection of process groups, typically one per terminal/login
  • Process Group: One or more processes treated as a unit for job control
  • Foreground Group: The group receiving terminal signals (Ctrl+C, Ctrl+Z)

When you run cat file | grep pattern | wc -l, all three commands share the same PGID - that's why they all die together on Ctrl+C!

CPU Scheduling

Linux uses the Completely Fair Scheduler (CFS) for normal processes:

  • Red-black tree: Processes sorted by virtual runtime
  • Fairness: Each process gets fair share proportional to priority
  • Time slices: Dynamic, based on number of runnable processes
  • Real-time classes: SCHED_FIFO and SCHED_RR for critical tasks

Context Switch

When the scheduler switches from one process to another:

  1. Save current process state (registers, PC) to memory
  2. Load new process state from memory
  3. Switch page tables (change memory view)
  4. Jump to new process's program counter

Context switches are expensive (~microseconds) so minimize thrashing!

Nice Values

Process priority controlled by "nice" value (-20 to +19):

NicePriorityBehavior
-20HighestLeast nice, hogs CPU
0DefaultNormal priority
+19LowestVery nice, yields CPU

Priority Commands

bash
# Start with lower priority
nice -n 10 ./cpu-intensive-task

# Change priority of running process
renice -n 5 -p 1234

# Require root for negative nice
sudo renice -n -10 -p 1234

# Real-time priority (requires root)
chrt -f 99 ./realtime-app   # SCHED_FIFO priority 99

Process Inspection & Control

Essential Process Commands

bash
# View all processes
ps aux

# Process tree showing relationships
pstree -p

# Watch processes in real-time
htop

# View process memory map
cat /proc/1234/maps

# View process status
cat /proc/1234/status

# Send signals
kill -SIGTERM 1234   # Request termination (15)
kill -SIGKILL 1234   # Force kill (9)
kill -SIGSTOP 1234   # Suspend (19)
kill -SIGCONT 1234   # Resume (18)

# Job control
command &      # Run in background
jobs           # List jobs
fg %1          # Bring to foreground
bg %1          # Send to background

Common Patterns

Fork-Exec Pattern (Shell executing command)

c
pid = fork();
if (pid == 0) {
    // Child: replace with new program
    exec("/bin/ls", args);
} else {
    // Parent: wait for child
    wait(&status);
}

Daemon Process Pattern

  1. fork() and parent exits (detach from terminal)
  2. setsid() to create new session
  3. Change directory to /
  4. Close stdin/stdout/stderr
  5. Write PID to /var/run/daemon.pid

If you found this explanation helpful, consider sharing it with others.

Mastodon