Processes

What a process is, its memory layout and PCB, process states, fork/exec/wait, zombies and orphans, and how context switching works.

Intermediate 4 min readLesson 3 of 16 Interview Q&A

A process is a program in execution: the code plus everything needed to run it — its own virtual address space, CPU register state, open files, and accounting information. Run the same program twice and you get two independent processes.

Inside a process

high addresseslow addressesKernel spacemapped but inaccessible from user modeStackone per thread; grows downMemory-mapped regionshared libraries, mmap'd filesHeapmalloc / new; grows upBSS + Datazeroed and initialised globalsTextprogram code (read-only, executable)

The kernel tracks each process in a process control block (PCB) — task_struct in Linux:

PCB fieldExample
IdentityPID, parent PID, user/group IDs
StateRunning, ready, blocked…
CPU contextSaved registers, program counter, stack pointer
MemoryPointer to page tables and memory regions
FilesFile descriptor table (0 = stdin, 1 = stdout, 2 = stderr, …)
SchedulingPriority, time used, which CPUs it may run on
Signals, limits, cgroup, namespacesPending signals, resource limits, container membership

Process states

admittedscheduledpreemptedexitI/O or waitI/O doneNewReadyRunningTerminatedBlocked (waiting)

Only one process per core can be Running. Ready processes wait in the scheduler's run queue. Blocked processes wait for an event (disk read, network data, a lock, a timer) and use no CPU.

Creating processes: fork, exec, wait

Unix splits process creation into two steps:

  • fork() clones the calling process. The child gets a copy of the parent's memory (shared copy-on-write, so it's cheap), its file descriptors and so on. fork returns twice: 0 in the child, the child's PID in the parent.
  • exec() replaces the current program with a new one (the PID stays the same).
  • wait() lets the parent wait for the child to exit and collect its exit status.
C
pid_t pid = fork();
if (pid == 0) {                       // child
    execlp("ls", "ls", "-l", NULL);   // becomes ls; only returns on error
    _exit(127);
} else {                              // parent
    int status;
    waitpid(pid, &status, 0);         // wait for the child
    printf("child exited with %d\n", WEXITSTATUS(status));
}

This is exactly how a shell runs your commands. Splitting fork and exec lets the child adjust its environment in between: redirect file descriptors (>), change directory, drop privileges.

Spawning processes from high-level languages
Process p = new ProcessBuilder("ls", "-l")
        .redirectErrorStream(true)
        .start();
String out = new String(p.getInputStream().readAllBytes());
int code = p.waitFor();

Zombies and orphans

  • Zombie — a child that has exited but whose parent hasn't called wait yet. Its PCB lingers (state Z in ps) to hold the exit status. A few are harmless; a parent that never reaps leaks PIDs.
  • Orphan — a child whose parent died first. It's re-parented to init (PID 1) or a "subreaper", which reaps it.

Context switching

Switching the CPU from process A to process B:

  1. A timer interrupt, a blocking system call or a yield enters the kernel.
  2. Save A's registers, PC and stack pointer into its PCB.
  3. The scheduler picks B.
  4. Switch the address space (load B's page-table root; with PCID the TLB needn't be flushed).
  5. Restore B's registers and return to user mode — B continues where it left off.

The direct cost is a few microseconds. The indirect cost is often larger: B starts with cold caches and TLB entries.

Signals

Signals are asynchronous notifications sent to a process:

SignalDefault actionTypical source
SIGINT (2)TerminateCtrl+C
SIGTERM (15)Terminatekill, orchestrators asking for a graceful shutdown
SIGKILL (9)Terminate — can't be caughtkill -9, the OOM killer
SIGSEGV (11)Core dumpInvalid memory access
SIGCHLDIgnoreA child exited
SIGHUPTerminateTerminal closed; often "reload config" for daemons

Servers should catch SIGTERM, stop accepting new work, finish in-flight requests and exit — a graceful shutdown, which Kubernetes relies on.

Key takeaways
  • A process = a program + a private address space + execution state + OS resources.
  • The PCB stores everything the kernel needs to pause and resume it.
  • States: new → ready ⇄ running → terminated, with blocked for waiting.
  • fork (copy-on-write clone) + exec (replace the program) + wait (reap).
  • Context switches save and restore CPU state; zombies await wait; orphans go to init.
Interview questions
QWhat's the difference between a process and a program?easy

A program is a passive file of instructions on disk. A process is an active instance of it, with memory, registers, open files and a PID. One program can run as many processes.

QWhy is fork() cheap even for a process using gigabytes of memory?medium

Copy-on-write: parent and child share the same physical pages, marked read-only. A page is copied only when one of them writes to it. Usually the child calls exec immediately, so almost nothing is copied.

QWhat is a zombie process and how do you get rid of it?medium

A process that has exited but hasn't been reaped by its parent with wait(). You can't kill a zombie (it's already dead); fix or kill the parent so it is reaped, or let init adopt and reap it.