Skip to content

Operating Systems 02 processes

Mugundan edited this page Nov 27, 2026 · 1 revision

Processes

Relevant source files

The following references were used as context for generating this wiki page:

A process is a program in execution. The program is a file on disk; the process is that program loaded into memory and running, with its own memory, its own open files and its own CPU state. Two people can run the same program at once, giving two separate processes. This page explains what a process contains, the states it moves through, how the OS switches between processes, and how processes are created and communicate.

Code on this page is illustrative C using the POSIX API.

Purpose and Scope

This page covers the process address space, the process control block (PCB), process states, context switches, fork, exec, wait and exit, zombie and orphan processes, and inter-process communication (IPC). Threads inside a process are on Threads; choosing which process runs is on CPU Scheduling.

The Recipe and the Cooking Analogy

Kitchen Computer
A recipe in a book A program (file on disk)
Someone actually cooking that recipe A process
Their worktop, ingredients and current step The process's memory and CPU state
A bookmark saying "stopped at step 4" The saved state in the PCB
Two cooks using the same recipe Two processes running the same program

What a Process Contains

flowchart TB
    subgraph AS["Address space of one process (low to high addresses)"]
        direction TB
        T["Text: the program's machine code (read-only)"]
        D["Data: global and static variables"]
        H["Heap: malloc / new, grows upward ↑"]
        G["... free space ..."]
        S["Stack: function calls, local variables, grows downward ↓"]
    end
    AS --- K["Plus, in the kernel: the PCB<br/>(registers, PC, open files, state...)"]
Loading
Part Holds Grows?
Text (code) Instructions No
Data / BSS Globals: initialised (data) and zero-initialised (BSS) No
Heap Dynamically allocated memory Up, via malloc / brk / mmap
Stack Return addresses, local variables, saved registers Down, one frame per call

Each process has its own private address space; one process cannot read another's memory unless they set up shared memory on purpose. See Memory Management.

The Process Control Block

The kernel keeps one PCB (Linux: task_struct) per process. It is the process's record card.

PCB field Example
Process ID (PID), parent PID 1234, 1
State Ready, running, waiting...
Saved CPU registers and program counter So it can resume exactly where it stopped
Scheduling info Priority, time used
Memory info Pointer to its page table
Open files File descriptor table: 0 = stdin, 1 = stdout, 2 = stderr, ...
Accounting, credentials User ID, CPU time used

Sources: Wikipedia: Process control block

Process States

stateDiagram-v2
    [*] --> New: created
    New --> Ready: admitted
    Ready --> Running: scheduler dispatches
    Running --> Ready: time slice ends (preempted)
    Running --> Waiting: waits for I/O or event
    Waiting --> Ready: I/O done / event happens
    Running --> Terminated: exit
    Terminated --> [*]
Loading
State Meaning
New Being created
Ready Could run, waiting for a CPU
Running On a CPU right now (at most one process per core)
Waiting (blocked) Cannot run until something happens: disk read, key press, lock
Terminated Finished; waiting for the parent to collect its exit status

Trap: a waiting process never goes straight back to Running; it goes to Ready and waits for the scheduler.

Sources: Wikipedia: Process (computing)

The Context Switch

To run another process, the kernel saves the current one's CPU state into its PCB and loads the next one's.

sequenceDiagram
    participant A as Process A
    participant K as Kernel
    participant B as Process B
    A->>K: timer interrupt (or system call that blocks)
    K->>K: save A's registers and PC into PCB(A)
    K->>K: scheduler picks B
    K->>K: load B's registers, PC, page table from PCB(B)
    K->>B: return to user mode, B continues
    Note over A,B: later the same happens in reverse
Loading

A context switch is pure overhead: no useful work is done. It typically costs microseconds directly, plus indirect costs because caches and the TLB now hold the old process's data. Switching between threads of the same process is cheaper because the address space (page table) stays the same.

Sources: Wikipedia: Context switch

Creating Processes: fork, exec, wait, exit

On Unix-like systems a new process is made in two steps: fork copies the current process, then exec replaces the copy's program with a new one.

Call What it does Returns
fork() Creates a child that is a copy of the parent 0 in the child, child's PID in the parent, -1 on error
exec*() (e.g. execvp) Replaces the current program with a new one; PID stays the same Does not return on success
wait() / waitpid() Parent waits for a child to finish and collects its exit status Child's PID
exit() Ends the process with a status Never returns
// illustrative: what a shell does to run "ls -l"
pid_t pid = fork();
if (pid == 0) {                       // child
    char *args[] = {"ls", "-l", NULL};
    execvp("ls", args);               // becomes ls
    perror("exec failed");            // only reached on error
    exit(1);
} else if (pid > 0) {                 // parent (the shell)
    int status;
    waitpid(pid, &status, 0);         // wait for ls to finish
} else {
    perror("fork failed");
}
flowchart TD
    S["Shell (PID 100)"] -->|"fork()"| P["Shell parent<br/>fork returns 200"]
    S -->|"fork()"| C["Child copy (PID 200)<br/>fork returns 0"]
    C -->|"exec('ls')"| L["PID 200 now runs ls"]
    L -->|"exit(0)"| Z["PID 200 finished"]
    P -->|"waitpid(200)"| Z
Loading

Modern kernels don't really copy all the memory at fork. They use copy-on-write: parent and child share pages until one of them writes. See Virtual Memory.

Sources: Wikipedia: Fork (system call)

Worked Problem: Counting fork()

// How many times is "hi" printed?
int main() {
    fork();
    fork();
    fork();
    printf("hi\n");
}

Each fork doubles the number of processes running the code after it.

flowchart TD
    P0["P0"] -->|"fork 1"| P0a["P0"]
    P0 -->|"fork 1"| P1["P1"]
    P0a -->|"fork 2"| P0b["P0"]
    P0a -->|"fork 2"| P2["P2"]
    P1 -->|"fork 2"| P1b["P1"]
    P1 -->|"fork 2"| P3["P3"]
    P0b -->|"fork 3"| X1["P0, P4"]
    P2 -->|"fork 3"| X2["P2, P5"]
    P1b -->|"fork 3"| X3["P1, P6"]
    P3 -->|"fork 3"| X4["P3, P7"]
Loading

After n forks in a row there are 2ⁿ processes: 8 processes, so "hi" is printed 8 times; 7 new processes were created.

A loop is the same: for (i = 0; i < n; i++) fork(); gives 2ⁿ processes.

Trap: printf("hi") without \n before a fork may print more times than expected, because the unflushed output buffer is copied into the child too.

Zombies and Orphans

flowchart LR
    subgraph Zombie["Zombie"]
        Z1["Child exits"] --> Z2["Parent has not called wait()"] --> Z3["Child stays as a PCB entry<br/>holding its exit status"]
    end
    subgraph Orphan["Orphan"]
        O1["Parent exits first"] --> O2["Child still running"] --> O3["Child is adopted by init (PID 1)<br/>which will wait() for it"]
    end
Loading
Zombie Orphan
What happened Child finished, parent hasn't collected it Parent finished, child still running
Uses A process-table entry (no memory, no CPU) A normal running process
Fixed by Parent calling wait; or the parent exiting, so init reaps it Automatic: init (or a subreaper) adopts it
Problem if Many pile up and the PID table fills Usually none

Sources: Wikipedia: Zombie process

Inter-Process Communication (IPC)

Processes have separate memory, so they need the kernel's help to talk.

Mechanism How it works Typical use
Pipe One-way byte stream between related processes (ls | grep x) Shell pipelines
Named pipe (FIFO) A pipe with a name in the file system Unrelated processes on one machine
Message queue Kernel-held queue of messages Structured messages
Shared memory Same physical pages mapped into both processes Fastest; needs explicit synchronization
Socket Byte stream or datagrams, local or over a network Client/server, networking
Signal Small asynchronous notification (SIGINT, SIGKILL) Ctrl-C, kill, child-exited notice
flowchart LR
    subgraph MP["Message passing (pipe, queue, socket)"]
        A1["Process A"] -->|"write: copy into kernel"| K1["Kernel buffer"] -->|"read: copy out"| B1["Process B"]
    end
    subgraph SM["Shared memory"]
        A2["Process A"] --> M["Shared pages"]
        B2["Process B"] --> M
    end
Loading
Message passing Shared memory
Speed Slower: data copied through the kernel Fastest: no copies after setup
Synchronization Built in (read blocks until data arrives) You must add locks or semaphores
Works across machines Yes (sockets) No

Sources: Wikipedia: Inter-process communication

Common Traps

  • A program is not a process; one program can be many processes.
  • fork returns twice: 0 in the child and the child's PID in the parent.
  • exec does not create a new process; it replaces the program in the current one (same PID).
  • A zombie has already finished; you cannot kill it, only reap it by having the parent call wait.

Interview Questions

  1. Process vs program? A program is passive code in a file; a process is an active execution with its own memory, registers and resources.
  2. What is in a PCB? PID, state, saved registers and PC, scheduling information, memory-management information, open files, credentials.
  3. What happens in a context switch? Save the running process's registers and PC into its PCB, choose the next process, restore its registers, switch the page table, return to user mode.
  4. Why fork then exec, not one call? Between them the child can change its own setup (redirect file descriptors, change directory, drop privileges) before running the new program. That is how shells implement > and |.
  5. How many processes does fork() called n times in sequence create? 2ⁿ in total, 2ⁿ − 1 new.
  6. Zombie vs orphan? Zombie: dead child not yet reaped by its parent. Orphan: live child whose parent died; init adopts it.

Key Points

  • A process is a running program: private address space (text, data, heap, stack) plus a PCB in the kernel.
  • States: ready, running, waiting; the scheduler moves processes between ready and running.
  • fork copies, exec replaces, wait reaps; IPC uses pipes, queues, sockets, signals or shared memory.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally