{}DSA Atlas

Processes

What a process is, its memory layout, the process control block, the five-state lifecycle, fork/exec/wait, zombies and orphans, context switching, and every inter-process communication mechanism.

Beginner → Intermediate8 interview questions

Program vs process

A program is a file. A process is an instance of a program being executed: it has its own address space, registers, open files, and a lifecycle managed by the kernel. The OS identifies each process by a PID.

Memory layout of a process

high addresses kernel space Stacklocals, return addrs mmap: libs, files Heap BSS (zeroed globals) Data (init. globals) Text (code, read-only) low addresses one stack per thread · grows down malloc / new · grows up (brk, mmap) int counter; → BSS int limit = 10; → Data shared between processes running the same binary
Virtual address space of a typical Linux process (not to scale).

The Process Control Block (PCB)

Everything the kernel knows about a process lives in its PCB (task_struct on Linux, ~10 KB):

FieldWhy it's needed
PID, PPIDidentity and parent/child tree
Staterunning, ready, blocked…
Saved registers & PCto resume exactly where it left off
Scheduling infopriority, nice value, virtual runtime, CPU affinity
Memory infopage-table root, list of memory regions (VMAs)
File descriptor table0=stdin, 1=stdout, 2=stderr, then opened files/sockets
Credentialsuid, gid, capabilities
Signalshandlers, mask, pending
AccountingCPU time, start time

Process states

New Ready Running Terminated Blocked admitted dispatched preempted (timer) exit waits for I/O / lock / event event completes
The five-state model. Blocked processes never go straight to Running — they become Ready first.

Linux shows these in ps as R (running or runnable), S (interruptible sleep), D (uninterruptible sleep — usually disk I/O), T (stopped), Z (zombie).

Some textbooks add suspended states (ready-suspended, blocked-suspended) for processes swapped out to disk by the medium-term scheduler.

Creating processes: fork, exec, wait

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();                 // returns twice
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {                     // child
        execlp("ls", "ls", "-l", NULL); // replace image with `ls -l`
        perror("exec");                 // only reached if exec failed
        _exit(127);
    }
    int status;                          // parent
    waitpid(pid, &status, 0);            // reap the child (no zombie)
    printf("child exited with %d\n", WEXITSTATUS(status));
    return 0;
}
import os

pid = os.fork()
if pid == 0:                       # child
    os.execvp("ls", ["ls", "-l"])
else:                              # parent
    _, status = os.waitpid(pid, 0)
    print("child exited with", os.waitstatus_to_exitcode(status))

Copy-on-write (COW)

After fork, parent and child share the same physical pages, marked read-only. The first write by either triggers a page fault, and the kernel copies just that page. This makes fork fast even for large processes, and is why fork+exec doesn't copy the parent's memory. (It's also why Redis can snapshot with fork — the child sees a frozen view of memory.)

Zombies and orphans

  • Zombie — exited, not yet reaped by wait. Holds a PID slot.
  • Orphan — parent died first; adopted and reaped by PID 1.

Context switching

Switching the CPU from one process to another means saving the old one's state into its PCB and loading the new one's. A process switch also changes the address space, which can flush the TLB (unless the CPU supports tagged TLBs: PCID on x86, ASID on ARM).

Direct costHidden cost
Thread switch (same process)~1 µscache warm-up
Process switch~2–5 µsTLB refill + cache warm-up
Mode switch (syscall, no switch)~0.1 µsminimal

This is why high-performance servers avoid one-thread-per-connection designs at very high concurrency, and why "too many threads" hurts throughput.

Inter-process communication (IPC)

Processes are isolated by design, so they need explicit mechanisms to cooperate.

MechanismDirectionRelated processes only?Data copied via kernel?Typical use
Pipeone-wayyesyesshell pipelines, parent ↔ child
Named pipe (FIFO)one-waynoyessimple local producer/consumer
Message queuemany-to-manynoyesdiscrete prioritised messages
Shared memoryanynono (after setup)high-throughput data (databases, browsers)
Unix domain sockettwo-waynoyeslocal services (Docker, Postgres), fd passing
TCP/UDP sockettwo-wayno (any machine)yesnetworked services
Signalone-waynon/anotifications: SIGTERM, SIGCHLD, SIGINT
Memory-mapped fileanynonoshared persistent data

Pipe example

int fds[2];
pipe(fds);                         // fds[0] = read end, fds[1] = write end
if (fork() == 0) {                 // child writes
    close(fds[0]);
    write(fds[1], "hello", 5);
    _exit(0);
}
close(fds[1]);                     // parent reads
char buf[16];
ssize_t n = read(fds[0], buf, sizeof buf);
import os

r, w = os.pipe()
if os.fork() == 0:          # child
    os.close(r)
    os.write(w, b"hello")
    os._exit(0)
os.close(w)                 # parent
print(os.read(r, 16))
os.wait()

Signals you should know

SignalDefaultMeaning
SIGINT (2)terminateCtrl-C
SIGTERM (15)terminatepolite shutdown request (what kill and Kubernetes send first)
SIGKILL (9)terminatecannot be caught or ignored
SIGSTOP / SIGCONTstop / continuejob control; SIGSTOP can't be caught
SIGCHLDignorea child changed state
SIGSEGVcore dumpinvalid memory access
SIGHUPterminateterminal closed; daemons often use it to reload config
SIGPIPEterminatewrote to a pipe/socket with no reader

Schedulers that manage processes

  • Long-term scheduler (job scheduler): decides which jobs are admitted into memory (batch systems; mostly absent in desktop OSes).
  • Short-term scheduler (CPU scheduler): picks the next ready task, runs many times per second — see CPU Scheduling.
  • Medium-term scheduler: swaps processes out to disk and back in to control the degree of multiprogramming.

Interview questions

0 / 8 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.