Repository navigation
Operating Systems 02 processes
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Process (computing)
- Wikipedia: Process control block
- Wikipedia: Context switch
- Wikipedia: Fork (system call)
- Wikipedia: Zombie process
- Wikipedia: Inter-process communication
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 3
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.
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.
| 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 |
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...)"]
| 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 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
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 --> [*]
| 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)
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
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
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
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)
// 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"]
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.
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
| 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
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
| 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
- A program is not a process; one program can be many processes.
-
forkreturns twice: 0 in the child and the child's PID in the parent. -
execdoes 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.
- Process vs program? A program is passive code in a file; a process is an active execution with its own memory, registers and resources.
- What is in a PCB? PID, state, saved registers and PC, scheduling information, memory-management information, open files, credentials.
- 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.
-
Why
forkthenexec, 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|. -
How many processes does
fork()called n times in sequence create? 2ⁿ in total, 2ⁿ − 1 new. - Zombie vs orphan? Zombie: dead child not yet reaped by its parent. Orphan: live child whose parent died; init adopts it.
- 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.
-
forkcopies,execreplaces,waitreaps; IPC uses pipes, queues, sockets, signals or shared memory.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look