Operating Systems Overview
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Operating system
- Wikipedia: Kernel (operating system)
- Wikipedia: System call
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts
- Book: Arpaci-Dusseau and Arpaci-Dusseau, Operating Systems: Three Easy Pieces (free online)
An operating system (OS) is the program that manages a computer's hardware and lets other programs share it safely. It decides which program runs on the CPU, gives each program its own memory, keeps files on disk, talks to devices, and stops programs from interfering with each other. This wiki explains the core ideas for complete beginners and is organised around the questions asked in operating systems interviews.
> How to read this wiki. Each page has an everyday analogy, diagrams, a worked problem where interviews use one, a "Common traps" list and a short set of interview questions with model answers. Diagrams, code and numbers are illustrative. Worked problems were calculated by hand for this wiki.
Purpose and Scope
| # | Page | Interview topics |
|---|---|---|
| 1 | Overview | What an OS does, kernel vs user mode, the big picture |
| 2 | Processes | Process states, PCB, context switch, fork/exec/wait, zombies, IPC |
| 3 | Threads | Thread vs process, user vs kernel threads, what threads share |
| 4 | CPU Scheduling | FCFS, SJF, SRTF, Round Robin, priority, MLFQ, worked Gantt charts |
| 5 | Synchronization | Race conditions, mutex, semaphore, condition variable, classic problems |
| 6 | Deadlock | Four conditions, prevention, avoidance (banker's), detection, priority inversion |
| 7 | Memory Management | Fragmentation, paging, segmentation, page tables, TLB |
| 8 | Virtual Memory | Demand paging, page faults, replacement (FIFO, LRU, OPT), thrashing, copy-on-write |
| 9 | Files and I/O | Inodes, links, journaling, disk scheduling, interrupts, DMA |
| 10 | Kernel and System Calls | System call path, interrupts vs traps, monolithic vs microkernel, boot |
| 11 | Interview Q&A and Glossary | Quick-fire questions and all terms in one place |
The hardware side (caches, cores, memory ordering) is in the Computer Architecture wiki.
The Hotel Analogy
| Hotel | Operating system |
|---|---|
| Guests | Programs (processes) |
| Front desk | The kernel |
| Rooms, each with its own key | Each process's private memory (address space) |
| Shared facilities: lift, pool, kitchen | CPU, disk, network, devices |
| Booking the pool by time slots | CPU scheduling |
| "Ask the front desk; don't go into the boiler room" | System calls; user mode cannot touch hardware directly |
| Security stops one guest entering another's room | Memory protection |
What an OS Does
flowchart TD
OS["Operating system"] --> P["Process management<br/>create, schedule, terminate"]
OS --> M["Memory management<br/>virtual memory, protection"]
OS --> F["File systems<br/>files, directories, permissions"]
OS --> IO["Device / I/O management<br/>drivers, interrupts"]
OS --> S["Security and protection<br/>users, permissions, isolation"]
OS --> N["Networking<br/>sockets, protocols"]
Two ways to describe the OS's job:
- Resource manager: shares limited CPU time, memory and devices fairly and efficiently between many programs.
- Abstraction provider: gives programs simple, portable ideas (processes, files, sockets, virtual memory) instead of raw hardware.
The Layers
flowchart TB
U["User programs<br/>browser, shell, your code"] --> L["Libraries<br/>libc, runtime"]
L -->|"system calls"| K["Kernel<br/>scheduler, memory manager, file systems, drivers"]
K --> H["Hardware<br/>CPU, memory, disk, network"]
style K fill:#eef
| Mode | Who runs in it | What it may do |
|---|---|---|
| User mode | Applications and libraries | Ordinary instructions only; cannot touch devices or other processes' memory |
| Kernel mode (supervisor) | The kernel | Everything: configure the MMU, talk to devices, disable interrupts |
The CPU enforces the two modes in hardware (on Arm, exception levels EL0 for user and EL1 for kernel). A program enters the kernel only through a system call, an interrupt or an exception, covered in Kernel and System Calls.
Sources: Wikipedia: Operating system, Wikipedia: Kernel (operating system)
Key Terms at a Glance
| Term | One-line meaning |
|---|---|
| Program | Code sitting in a file |
| Process | A program being run: code + memory + open files + CPU state |
| Thread | One flow of execution inside a process |
| Kernel | The always-resident core of the OS that runs in kernel mode |
| System call | A request from a program to the kernel (read, fork, mmap) |
| Context switch | Saving one thread's CPU state and loading another's |
| Virtual memory | Each process sees its own private address space |
How to Prepare for OS Interviews
| Interviewers often ask you to... | Practise on |
|---|---|
| Explain the difference between two things (process vs thread, mutex vs semaphore) | Every page's "Interview questions" |
| Work a small problem on a whiteboard (Gantt chart, banker's algorithm, page faults) | Scheduling, Deadlock, Virtual Memory, Files and I/O |
| Write synchronization code (producer-consumer, thread-safe counter) | Synchronization |
Trace what happens end to end ("what happens when you run ls?") | Kernel and System Calls, Interview Q&A |
Count processes created by fork() | Processes |
Interview Questions
- What is an operating system? Software that manages hardware resources and provides common services and abstractions to programs.
- Why do we need user and kernel mode? So a buggy or malicious program cannot crash the machine, read other programs' memory, or access devices directly; it must ask the kernel.
- Is the shell part of the kernel? No. The shell is an ordinary user program that makes system calls such as
fork,execandwait.
Key Points
- The OS manages CPU, memory, storage and devices, and provides processes, files and virtual memory.
- The kernel runs in privileged mode; programs reach it only through system calls, interrupts and exceptions.
- Interviews test definitions, comparisons, small worked problems and end-to-end traces.
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.
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...)"]
| 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 --> [*]
| 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
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
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"]
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
| 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
| 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.
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.
Interview Questions
- 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.
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.
forkcopies,execreplaces,waitreaps; IPC uses pipes, queues, sockets, signals or shared memory.
Threads
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Thread (computing)
- Wikipedia: Context switch
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 4
A thread is one flow of execution inside a process. A process starts with one thread; it can create more, and all of them share the process's memory and open files while each keeps its own registers and stack. Threads let one program do several things at once, for example a browser downloading a page while still responding to clicks.
> Code on this page is illustrative C using POSIX threads (pthread).
Purpose and Scope
This page covers what threads share and what each owns, threads versus processes, user-level versus kernel-level threads and the threading models, thread pools, and why threads need synchronization. Locks themselves are on Synchronization.
The Shared Office Analogy
| Office | Process with threads |
|---|---|
| One office (rooms, filing cabinets, phone line) | One process: address space, open files |
| Several workers in that office | Several threads |
| Each worker's own notepad and current task | Each thread's own registers, PC and stack |
| Everyone can open every filing cabinet | Every thread can read and write all the process's memory |
| Two workers editing the same file at once | A race condition: needs a lock |
A separate process would be a separate office: safer, but sharing papers means posting them (IPC).
What Threads Share and Own
flowchart TB
subgraph P["One process"]
direction TB
SH["Shared by all threads:<br/>code, globals, heap,<br/>open files, signal handlers, PID"]
subgraph T1["Thread 1"]
R1["registers, PC"]
S1["own stack"]
end
subgraph T2["Thread 2"]
R2["registers, PC"]
S2["own stack"]
end
subgraph T3["Thread 3"]
R3["registers, PC"]
S3["own stack"]
end
end
| Shared (per process) | Private (per thread) |
|---|---|
| Code (text) | Program counter |
| Global and static variables | Registers |
| Heap | Stack (local variables, call frames) |
| Open file descriptors | Thread ID |
| Current directory, user ID | Thread-local storage (thread_local) |
| Signal handlers | Signal mask, scheduling state |
Trap: a thread's stack is private by convention, not protected. Another thread holding a pointer to it can still read or overwrite it.
Threads versus Processes
| Process | Thread | |
|---|---|---|
| Memory | Own address space | Shares the process's address space |
| Creation cost | Higher (new page tables, PCB) | Lower |
| Context switch | Slower: page table and TLB change | Faster: same address space |
| Communication | IPC through the kernel | Just read and write shared variables |
| A crash (bad pointer) | Kills only that process | Kills the whole process, all threads |
| Isolation | Strong | None between threads |
Typical choices: browsers use a process per tab for isolation and threads inside each; servers use a pool of threads for speed.
Sources: Wikipedia: Thread (computing)
Creating Threads
// illustrative
#include <pthread.h>
#include <stdio.h>
void *worker(void *arg) {
int id = *(int *)arg;
printf("hello from thread %d\n", id);
return NULL;
}
int main(void) {
pthread_t t[4];
int ids[4];
for (int i = 0; i < 4; i++) {
ids[i] = i; // one slot per thread, not &i
pthread_create(&t[i], NULL, worker, &ids[i]);
}
for (int i = 0; i < 4; i++)
pthread_join(t[i], NULL); // wait for each thread
return 0;
}
The output order of the four lines can differ from run to run: the scheduler decides which thread runs when.
Trap: passing &i to every thread is a classic bug; all threads share one i that keeps changing.
User-Level and Kernel-Level Threads
| User-level threads | Kernel-level threads | |
|---|---|---|
| Managed by | A library in the process | The kernel |
| Kernel knows about them? | No: sees one thread | Yes: schedules each one |
| Switch cost | Very cheap (no system call) | Needs the kernel |
| One thread blocks on I/O | The whole process blocks | Only that thread blocks |
| Use multiple cores | No | Yes |
Threading Models
flowchart LR
subgraph M1["Many-to-one"]
u1["U"] --> k1["K"]
u2["U"] --> k1
u3["U"] --> k1
end
subgraph OO["One-to-one"]
a1["U"] --> b1["K"]
a2["U"] --> b2["K"]
a3["U"] --> b3["K"]
end
subgraph MM["Many-to-many"]
c1["U"] --> d1["K"]
c2["U"] --> d1
c3["U"] --> d2["K"]
c4["U"] --> d2
end
| Model | Description | Example |
|---|---|---|
| Many-to-one | All user threads on one kernel thread | Old "green threads" |
| One-to-one | Each user thread is a kernel thread | Linux pthreads, Windows threads |
| Many-to-many | M user threads multiplexed on N kernel threads | Go goroutines, Erlang processes (runtime schedulers) |
Thread Pools
Creating a thread for each request wastes time and can create too many threads. A thread pool creates a fixed set of worker threads once; work items go into a queue and idle workers take them.
flowchart LR
R1["Request"] --> Q["Work queue"]
R2["Request"] --> Q
R3["Request"] --> Q
Q --> W1["Worker 1"]
Q --> W2["Worker 2"]
Q --> W3["Worker 3"]
The queue itself is a producer-consumer buffer, see Synchronization.
Concurrency versus Parallelism
| Meaning | Needs multiple cores? | |
|---|---|---|
| Concurrency | Several tasks make progress over the same period, possibly by taking turns | No |
| Parallelism | Several tasks run at the same instant | Yes |
flowchart TB
subgraph C["Concurrent on 1 core"]
c["A A B B A B A A"]
end
subgraph P["Parallel on 2 cores"]
p1["core 0: A A A A"]
p2["core 1: B B B B"]
end
Why Threads Need Care
Because threads share memory, two threads updating the same variable can interfere:
// illustrative: two threads each run this 1,000,000 times
counter++; // load, add 1, store: three steps, not one
The final value is often less than 2,000,000, because both threads can load the same old value before either stores. Fixing this is the subject of Synchronization.
Common Traps
- Threads share the heap and globals but not the stack or registers.
- A segfault in one thread kills the whole process.
- Output order between threads is not guaranteed without synchronization.
- User-level threads alone cannot use more than one core.
Interview Questions
- Process vs thread? A process has its own address space; threads within a process share it, each with its own registers and stack. Threads are cheaper to create and switch but give no isolation.
- What do threads in one process share? Code, globals, heap, open files, signal handlers. Not stacks, registers or program counters.
- Why is a thread switch cheaper than a process switch? The page table stays the same, so there is no address-space switch and the TLB and caches stay warm.
- User vs kernel threads? User threads are managed by a library and invisible to the kernel; cheap but one blocking call blocks all, and no multicore. Kernel threads are scheduled individually by the kernel.
- Concurrency vs parallelism? Concurrency is dealing with many things at once (interleaving); parallelism is doing many things at once (multiple cores).
- Why use a thread pool? It avoids the cost of creating threads per task and bounds the number of threads.
Key Points
- A thread is an execution flow inside a process: own registers, PC and stack; shared memory and files.
- Threads are cheaper than processes but give no isolation; shared data needs synchronization.
- Linux uses one-to-one kernel threads; runtimes like Go multiplex many user threads on few kernel threads.
CPU Scheduling
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Scheduling (computing)
- Wikipedia: Round-robin scheduling
- Wikipedia: Multilevel feedback queue
- Wikipedia: Completely Fair Scheduler
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 5
There are usually more ready threads than CPU cores. The scheduler is the part of the kernel that decides which ready thread runs next, and for how long. Different rules favour different goals: finishing jobs quickly on average, responding fast to the user, or being fair. Working out a schedule by hand on a Gantt chart is one of the most common OS interview questions.
> All schedules on this page were worked out by hand for one example and re-checked; they are illustrative.
Purpose and Scope
This page covers the metrics (turnaround, waiting, response time), preemptive versus non-preemptive scheduling, FCFS, SJF, SRTF, Round Robin, priority scheduling with aging, multilevel feedback queues, a short note on Linux's scheduler, and a full worked example. Process states are on Processes.
The Supermarket Checkout Analogy
| Checkout rule | Scheduling algorithm |
|---|---|
| Serve people in the order they joined | FCFS |
| Let the person with the fewest items go first | SJF |
| Let anyone with fewer items than the person being served jump in | SRTF |
| Serve each person for 1 minute, then send them to the back of the queue | Round Robin |
| Serve VIPs first | Priority |
| VIPs first, but anyone who has waited long becomes a VIP | Priority with aging |
The Measures
| Measure | Formula | Who cares |
|---|---|---|
| Turnaround time (TAT) | Completion time − arrival time | Batch jobs: "how long until my job finished?" |
| Waiting time | Turnaround − burst time (time spent in the ready queue) | Most textbook questions |
| Response time | First time on the CPU − arrival time | Interactive users |
| Throughput | Jobs finished per unit time | Servers |
| CPU utilisation | Fraction of time the CPU is busy | Everyone |
A burst is how long a job needs the CPU before it finishes or blocks.
Preemptive or Not
flowchart TD
R["A thread is running"] --> Q{"Can the scheduler take<br/>the CPU away before it<br/>finishes or blocks?"}
Q -->|"No"| NP["Non-preemptive<br/>FCFS, SJF"]
Q -->|"Yes, on a timer or<br/>a better arrival"| P["Preemptive<br/>SRTF, Round Robin,<br/>preemptive priority"]
Every general-purpose OS today is preemptive: a hardware timer interrupt returns control to the kernel regularly so one thread cannot hog the CPU.
The Algorithms
| Algorithm | Picks | Preemptive? | Strength | Weakness |
|---|---|---|---|---|
| FCFS (first come, first served) | Earliest arrival | No | Simple, no starvation | Convoy effect: short jobs stuck behind a long one |
| SJF (shortest job first) | Shortest burst among arrived jobs | No | Minimum average waiting time (non-preemptive) | Needs burst lengths in advance; long jobs can starve |
| SRTF (shortest remaining time first) | Shortest remaining time; re-check on every arrival | Yes | Lowest average waiting time overall | Same as SJF, plus more switches |
| Round Robin (RR) | Next in queue, for at most one quantum q | Yes | Good response time, fair, no starvation | Higher average turnaround; overhead if q is tiny |
| Priority | Highest priority | Either | Lets important work go first | Starvation of low priority; fix with aging |
| MLFQ | Highest non-empty queue; demote CPU hogs | Yes | Favours interactive jobs without knowing bursts | Many parameters to tune |
Sources: Wikipedia: Scheduling (computing)
Worked Example
Four processes:
| Process | Arrival | Burst |
|---|---|---|
| P1 | 0 | 8 |
| P2 | 1 | 4 |
| P3 | 2 | 9 |
| P4 | 3 | 5 |
The method is the same for every algorithm:
flowchart LR
A["Draw the Gantt chart<br/>time by time"] --> B["Read each process's<br/>completion time"]
B --> C["TAT = completion − arrival"]
C --> D["Waiting = TAT − burst"]
D --> E["Average over all processes"]
FCFS
| P1 | P2 | P3 | P4 |
0 8 12 21 26
| Process | Completion | TAT | Waiting |
|---|---|---|---|
| P1 | 8 | 8 | 0 |
| P2 | 12 | 11 | 7 |
| P3 | 21 | 19 | 10 |
| P4 | 26 | 23 | 18 |
| Average | 15.25 | 8.75 |
SJF (non-preemptive)
At time 0 only P1 has arrived, so it runs to the end. At time 8 the shortest of P2 (4), P3 (9), P4 (5) is P2, then P4, then P3.
| P1 | P2 | P4 | P3 |
0 8 12 17 26
| Process | Completion | TAT | Waiting |
|---|---|---|---|
| P1 | 8 | 8 | 0 |
| P2 | 12 | 11 | 7 |
| P3 | 26 | 24 | 15 |
| P4 | 17 | 14 | 9 |
| Average | 14.25 | 7.75 |
SRTF (preemptive SJF)
| Time | Event | Remaining times | Runs |
|---|---|---|---|
| 0 | P1 arrives | P1=8 | P1 |
| 1 | P2 arrives | P1=7, P2=4 | P2 (4 < 7, preempts P1) |
| 2 | P3 arrives | P1=7, P2=3, P3=9 | P2 |
| 3 | P4 arrives | P1=7, P2=2, P3=9, P4=5 | P2 |
| 5 | P2 done | P1=7, P3=9, P4=5 | P4 |
| 10 | P4 done | P1=7, P3=9 | P1 |
| 17 | P1 done | P3=9 | P3 |
| 26 | P3 done |
|P1| P2 | P4 | P1 | P3 |
0 1 5 10 17 26
| Process | Completion | TAT | Waiting |
|---|---|---|---|
| P1 | 17 | 17 | 9 |
| P2 | 5 | 4 | 0 |
| P3 | 26 | 24 | 15 |
| P4 | 10 | 7 | 2 |
| Average | 13.00 | 6.50 |
Round Robin, quantum = 4
Convention: a process arriving during a quantum joins the queue before the process that was just preempted.
| Time slice | Runs | Remaining after | Ready queue after |
|---|---|---|---|
| 0-4 | P1 | P1=4 | P2, P3, P4, P1 |
| 4-8 | P2 | P2 done | P3, P4, P1 |
| 8-12 | P3 | P3=5 | P4, P1, P3 |
| 12-16 | P4 | P4=1 | P1, P3, P4 |
| 16-20 | P1 | P1 done | P3, P4 |
| 20-24 | P3 | P3=1 | P4, P3 |
| 24-25 | P4 | P4 done | P3 |
| 25-26 | P3 | P3 done |
| P1 | P2 | P3 | P4 | P1 | P3 |P4|P3|
0 4 8 12 16 20 24 25 26
| Process | Completion | TAT | Waiting | Response |
|---|---|---|---|---|
| P1 | 20 | 20 | 12 | 0 |
| P2 | 8 | 7 | 3 | 3 |
| P3 | 26 | 24 | 15 | 6 |
| P4 | 25 | 22 | 17 | 9 |
| Average | 18.25 | 11.75 | 4.50 |
Comparing the Results
| Algorithm | Avg turnaround | Avg waiting | Avg response |
|---|---|---|---|
| FCFS | 15.25 | 8.75 | 8.75 |
| SJF | 14.25 | 7.75 | 7.75 |
| SRTF | 13.00 | 6.50 | 4.25 |
| RR (q = 4) | 18.25 | 11.75 | 4.50 |
SRTF wins on averages, as theory says it must, but only because it knew every burst length in advance. RR has the worst turnaround but its response time does not depend on knowing anything, and it guarantees each process gets the CPU within (n − 1) × q of waiting. For non-preemptive algorithms response time equals waiting time.
Sources: Wikipedia: Round-robin scheduling
Choosing the Round Robin Quantum
flowchart LR
S["Quantum too small"] -->|"many context switches,<br/>overhead dominates"| M["Good quantum<br/>a bit longer than<br/>most interactive bursts"]
L["Quantum too large"] -->|"behaves like FCFS,<br/>poor response"| M
A common rule of thumb is that about 80% of CPU bursts should finish within one quantum.
Priority Scheduling and Aging
Each process has a priority number (in many textbooks a smaller number means higher priority). The danger is starvation: a steady stream of high-priority work means low-priority work never runs. Aging raises the priority of a process the longer it waits, so eventually it runs.
Multilevel Feedback Queue (MLFQ)
The scheduler doesn't know burst lengths, so MLFQ learns them from behaviour:
flowchart TD
N["New job"] --> Q0["Queue 0: highest priority, q = 8 ms"]
Q0 -->|"used whole quantum<br/>(looks CPU-bound)"| Q1["Queue 1: q = 16 ms"]
Q1 -->|"used whole quantum"| Q2["Queue 2: lowest, FCFS"]
Q0 -->|"blocked for I/O early<br/>(looks interactive): stays"| Q0
Q2 -->|"periodic priority boost<br/>(prevents starvation)"| Q0
Rules: run the highest non-empty queue; a job that uses its whole quantum is demoted; a job that gives up the CPU early stays; every so often all jobs are boosted back to the top. Interactive jobs stay at high priority and respond quickly, while CPU-heavy jobs sink.
Sources: Wikipedia: Multilevel feedback queue
What Linux Does
For ordinary threads, Linux long used the Completely Fair Scheduler (CFS). It tracks each thread's virtual runtime (CPU time used, scaled by its nice weight) in a red-black tree and always runs the thread with the smallest virtual runtime, so CPU time is shared in proportion to weight. Since kernel 6.6 the default fair scheduler is EEVDF, which keeps the same weighted-fairness idea and adds a deadline to favour latency-sensitive threads. Real-time threads (SCHED_FIFO, SCHED_RR) use fixed priorities and always beat ordinary threads.
Sources: Wikipedia: Completely Fair Scheduler
Multicore Scheduling Notes
| Idea | Meaning |
|---|---|
| Per-core run queues | Each core has its own queue, avoiding one shared lock |
| Load balancing | Idle cores pull (or busy cores push) threads from others |
| Processor affinity | Prefer to keep a thread on the same core so its cache stays warm |
Common Traps
- Waiting time is turnaround minus burst, not "start time minus arrival" (that is response time, and they differ for preemptive algorithms).
- In SJF, only jobs that have already arrived can be chosen.
- State your Round Robin tie-break convention; different textbooks put new arrivals before or after the preempted job.
- The CPU may be idle if no job has arrived yet; leave a gap in the Gantt chart.
Interview Questions
- Preemptive vs non-preemptive? Preemptive scheduling can stop a running thread (timer, higher-priority arrival); non-preemptive waits until it blocks or finishes.
- Which algorithm gives minimum average waiting time? SJF among non-preemptive algorithms, SRTF overall, but both need burst lengths and can starve long jobs.
- What is the convoy effect? In FCFS, many short jobs wait behind one long job, lowering utilisation and raising average wait.
- How do you prevent starvation in priority scheduling? Aging: gradually raise the priority of waiting processes.
- What happens if the RR quantum is very large? Very small? Large: it becomes FCFS. Small: context-switch overhead dominates.
- How does MLFQ estimate burst length? By behaviour: jobs using whole quanta are demoted; jobs that block early stay high. Periodic boosts prevent starvation.
Key Points
- Turnaround = completion − arrival; waiting = turnaround − burst; response = first run − arrival.
- SJF/SRTF minimise average waiting but need burst knowledge; RR gives good response and fairness.
- Real schedulers (MLFQ, CFS/EEVDF) approximate these goals without knowing the future.
Synchronization
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Race condition
- Wikipedia: Mutual exclusion
- Wikipedia: Semaphore (programming)
- Wikipedia: Monitor (synchronization)
- Wikipedia: Spinlock
- Wikipedia: Producer–consumer problem
- Wikipedia: Readers–writers problem
- Wikipedia: Dining philosophers problem
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapters 6-7
When threads share data, the result can depend on the exact order in which they run. Synchronization is the set of tools (locks, semaphores, condition variables) that force the order to be safe. This is the topic interviewers probe most deeply, often by asking you to write code.
> Code on this page is illustrative C with POSIX threads and semaphores. It is written to show the pattern clearly; error checking is omitted.
Purpose and Scope
This page covers race conditions, critical sections and their three requirements, atomic instructions, spinlocks and mutexes, semaphores, condition variables and monitors, and the three classic problems: producer-consumer, readers-writers and dining philosophers. Deadlock is on Deadlock.
The Bathroom Key Analogy
| Café | Synchronization |
|---|---|
| One bathroom | A critical section: code that touches shared data |
| One key on a hook | A mutex |
| Take the key, use it, hang it back | lock() / unlock() |
| Waiting by the door checking constantly | A spinlock |
| Sitting down until called | A blocking mutex |
| A car park with a "spaces: 5" counter | A counting semaphore |
The Race Condition
// illustrative: shared by two threads
int counter = 0;
void *add(void *_) { for (int i = 0; i < 1000000; i++) counter++; return NULL; }
counter++ is really three steps:
load r, counter
add r, r, 1
store counter, r
sequenceDiagram
participant A as Thread A
participant M as counter (memory)
participant B as Thread B
A->>M: load (reads 5)
B->>M: load (reads 5)
A->>A: add -> 6
B->>B: add -> 6
A->>M: store 6
B->>M: store 6
Note over M: two increments, value only went up by 1
A race condition is when the result depends on the timing of threads. The code that touches shared data is the critical section.
Sources: Wikipedia: Race condition
What a Correct Solution Needs
| Requirement | Meaning |
|---|---|
| Mutual exclusion | At most one thread is in the critical section at a time |
| Progress | If nobody is inside and someone wants in, someone gets in; no needless blocking |
| Bounded waiting | A waiting thread gets in after a bounded number of others go first (no starvation) |
Peterson's algorithm meets all three for two threads using only loads and stores, and is a common textbook question. On modern CPUs it needs memory barriers to work, because hardware may reorder its loads and stores (see the Architecture wiki: Memory and Ordering). Real systems use atomic instructions instead.
Hardware Atomics
The CPU provides instructions that read and write a location as one indivisible step:
| Primitive | What it does |
|---|---|
| Test-and-set | Set a flag to 1 and return its old value |
| Compare-and-swap (CAS) | If the value equals expected, replace it with new; report success |
| Fetch-and-add | Add to a value and return the old one |
// illustrative: a fixed counter with C11 atomics
#include <stdatomic.h>
atomic_int counter = 0;
atomic_fetch_add(&counter, 1); // one indivisible increment
All locks are built on these.
Spinlocks and Mutexes
// illustrative spinlock using test-and-set
atomic_flag lock = ATOMIC_FLAG_INIT;
void acquire(void) { while (atomic_flag_test_and_set(&lock)) { /* spin */ } }
void release(void) { atomic_flag_clear(&lock); }
| Spinlock | Mutex (blocking lock) | |
|---|---|---|
| While waiting | Loops, burning CPU | Thread sleeps; kernel wakes it |
| Good when | The lock is held for a very short time, on multicore | The wait might be long |
| Bad when | Lock held long, or only one core | Very short sections (sleep/wake overhead) |
| Used in | Kernels, interrupt handlers | Most application code (pthread_mutex_t) |
Real mutexes often spin briefly, then sleep (Linux futex-based mutexes do this).
// illustrative: the counter fixed with a mutex
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *add(void *_) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&m);
counter++; // critical section
pthread_mutex_unlock(&m);
}
return NULL;
}
Sources: Wikipedia: Spinlock, Wikipedia: Mutual exclusion
Semaphores
A semaphore is an integer with two atomic operations:
| Operation | Also called | Effect |
|---|---|---|
wait(S) | P, down, sem_wait | Decrement; if the result would be negative, block |
signal(S) | V, up, sem_post | Increment; wake one waiting thread if any |
flowchart TD
W["wait(S)"] --> C{"S > 0 ?"}
C -->|"yes"| D["S = S - 1, continue"]
C -->|"no"| B["block on S's queue"]
SG["signal(S)"] --> Q{"anyone blocked?"}
Q -->|"yes"| WK["wake one"]
Q -->|"no"| INC["S = S + 1"]
| Kind | Initial value | Used for |
|---|---|---|
| Binary semaphore | 1 | Mutual exclusion (like a mutex) |
| Counting semaphore | N | N identical resources (buffer slots, connections) |
| Signalling semaphore | 0 | "Wait until event happens" between threads |
Mutex versus Binary Semaphore
| Mutex | Binary semaphore | |
|---|---|---|
| Ownership | Only the thread that locked it may unlock it | Any thread may signal |
| Purpose | Mutual exclusion | Mutual exclusion or signalling |
| Priority inheritance | Often supported | Usually not |
Sources: Wikipedia: Semaphore (programming)
Condition Variables and Monitors
A condition variable lets a thread sleep until some condition on shared data becomes true. It is always used with a mutex.
| Call | Effect |
|---|---|
pthread_cond_wait(&cv, &m) | Atomically release m and sleep; re-acquire m before returning |
pthread_cond_signal(&cv) | Wake one waiter |
pthread_cond_broadcast(&cv) | Wake all waiters |
// illustrative pattern: always re-check in a while loop
pthread_mutex_lock(&m);
while (!ready) // not "if": spurious wakeups, other threads may get there first
pthread_cond_wait(&cv, &m);
/* ready is true and we hold m */
pthread_mutex_unlock(&m);
A monitor packages shared data, a lock and condition variables together so that only one thread is inside at a time. Java synchronized methods with wait/notify are a monitor.
Sources: Wikipedia: Monitor (synchronization)
Classic Problem 1: Producer-Consumer (Bounded Buffer)
Producers put items into a buffer of N slots; consumers take them out. Producers must wait when it is full, consumers when it is empty.
flowchart LR
P1["Producer"] --> B["Buffer: N slots<br/>empty = free slots<br/>full = filled slots"]
P2["Producer"] --> B
B --> C1["Consumer"]
B --> C2["Consumer"]
// illustrative: three semaphores
sem_t empty; // sem_init(&empty, 0, N) free slots
sem_t full; // sem_init(&full, 0, 0) filled slots
sem_t mutex; // sem_init(&mutex, 0, 1) protects the buffer indices
void producer(item x) {
sem_wait(&empty); // wait for a free slot
sem_wait(&mutex);
buffer[in] = x; in = (in + 1) % N;
sem_post(&mutex);
sem_post(&full); // one more filled slot
}
item consumer(void) {
sem_wait(&full); // wait for a filled slot
sem_wait(&mutex);
item x = buffer[out]; out = (out + 1) % N;
sem_post(&mutex);
sem_post(&empty); // one more free slot
return x;
}
Trap: swapping the order to sem_wait(&mutex) then sem_wait(&empty) can deadlock. A producer holding the mutex sleeps on a full buffer, and no consumer can get the mutex to empty it.
Sources: Wikipedia: Producer–consumer problem
Classic Problem 2: Readers-Writers
Many readers may read together, but a writer needs exclusive access.
// illustrative: "readers-preference" solution
sem_t rw_mutex; // 1: held by a writer, or by the group of readers
sem_t mutex; // 1: protects read_count
int read_count = 0;
void reader(void) {
sem_wait(&mutex);
if (++read_count == 1) sem_wait(&rw_mutex); // first reader locks writers out
sem_post(&mutex);
/* read */
sem_wait(&mutex);
if (--read_count == 0) sem_post(&rw_mutex); // last reader lets writers in
sem_post(&mutex);
}
void writer(void) {
sem_wait(&rw_mutex);
/* write */
sem_post(&rw_mutex);
}
This version can starve writers if readers keep arriving. Writer-preference or fair versions exist; in practice use pthread_rwlock_t.
Sources: Wikipedia: Readers–writers problem
Classic Problem 3: Dining Philosophers
Five philosophers sit round a table with one fork between each pair. Each needs both neighbouring forks to eat.
flowchart LR
P0((P0)) --- F0[fork 0] --- P1((P1)) --- F1[fork 1] --- P2((P2)) --- F2[fork 2] --- P3((P3)) --- F3[fork 3] --- P4((P4)) --- F4[fork 4] --- P0
If every philosopher picks up the left fork first, all five can hold one fork and wait forever for the other: deadlock.
| Fix | Why it works |
|---|---|
| Order the forks: always pick the lower-numbered fork first | Breaks circular wait (one philosopher picks right first) |
| Allow at most 4 to sit at once (a semaphore of 4) | At least one can always get both forks |
| Pick up both forks only if both are free (inside a monitor) | No one holds one fork while waiting |
Sources: Wikipedia: Dining philosophers problem
Common Traps
counter++andx = x + 1are not atomic.- Always wait on a condition variable inside a
whileloop, not anif. - In producer-consumer, wait on the counting semaphore before the mutex.
volatilein C does not make code thread-safe; use atomics or locks.- Hold locks for as short a time as possible; never do slow I/O while holding a lock if you can avoid it.
Interview Questions
- What is a race condition? A bug where the outcome depends on the relative timing of threads accessing shared data, at least one of them writing.
- Mutex vs semaphore? A mutex is a lock with an owner, for mutual exclusion. A semaphore is a counter that any thread can signal, for counting resources or signalling events.
- Spinlock vs mutex: when would you use a spinlock? For very short critical sections on a multicore machine, or in kernel code that cannot sleep (interrupt context).
- Why must
cond_waitbe in a loop? Wakeups can be spurious, and another thread may have consumed the condition before this one re-acquires the lock. - Write producer-consumer with semaphores. Use
empty= N,full= 0,mutex= 1, as above. - How do you avoid deadlock in dining philosophers? Impose a global order on the forks, or limit the number of diners to N − 1.
- What does CAS do and how is a lock built from it? It atomically swaps a value only if it equals an expected value; a lock loops on CAS(lock, 0, 1).
Key Points
- A critical section needs mutual exclusion, progress and bounded waiting.
- Locks are built on atomic instructions; spinlocks busy-wait, mutexes sleep.
- Semaphores count resources; condition variables wait for a condition under a mutex. Know the three classic problems.
Deadlock
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Deadlock (computer science)
- Wikipedia: Banker's algorithm
- Wikipedia: Priority inversion
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 8
A deadlock is a situation where a group of threads are all waiting for each other, so none of them can ever continue. It is the most common bug that locks introduce. Interviews ask for the four necessary conditions, the ways to handle deadlock, and a worked banker's algorithm.
> The banker's algorithm example on this page was computed with a short script and checked by hand.
Purpose and Scope
This page covers the four Coffman conditions, resource-allocation graphs, the four strategies (prevention, avoidance, detection and recovery, ignoring), the banker's algorithm with a worked example, livelock, starvation and priority inversion. Locks themselves are on Synchronization.
The Narrow Bridge Analogy
Two cars meet in the middle of a one-lane bridge. Neither can go forward, and neither will reverse. Each holds part of the bridge and wants the part the other holds.
flowchart LR
A["Thread A<br/>holds lock 1"] -->|"waits for"| L2["lock 2"]
B["Thread B<br/>holds lock 2"] -->|"waits for"| L1["lock 1"]
L1 -.->|"held by"| A
L2 -.->|"held by"| B
// illustrative: the classic two-lock deadlock
// Thread A // Thread B
pthread_mutex_lock(&m1); pthread_mutex_lock(&m2);
pthread_mutex_lock(&m2); // waits pthread_mutex_lock(&m1); // waits
The Four Necessary Conditions (Coffman)
A deadlock can happen only if all four hold at once. Break any one and deadlock is impossible.
| Condition | Meaning | How to break it |
|---|---|---|
| Mutual exclusion | A resource can be held by only one thread | Use sharable resources (read-only data, lock-free structures); often impossible |
| Hold and wait | A thread holds one resource while waiting for another | Request all resources at once, or release everything before asking for more |
| No preemption | Resources can't be taken away forcibly | Allow taking them (e.g. trylock and back off, roll back a transaction) |
| Circular wait | A cycle of threads, each waiting for the next | Lock ordering: always acquire locks in one global order |
Lock ordering is the most practical fix and the answer interviewers usually want.
Sources: Wikipedia: Deadlock (computer science)
Resource-Allocation Graphs
Draw threads as circles and resources as boxes. An arrow from thread to resource means "requests"; from resource to thread means "held by".
flowchart LR
T1((T1)) -->|"requests"| R2[R2]
R2 -->|"held by"| T2((T2))
T2 -->|"requests"| R1[R1]
R1 -->|"held by"| T1
| Graph | Conclusion |
|---|---|
| No cycle | No deadlock |
| Cycle, one instance of each resource | Deadlock |
| Cycle, several instances of some resource | Possible deadlock; must check further |
Four Strategies
flowchart TD
D["Handling deadlock"] --> P["Prevention<br/>design so one condition<br/>can never hold"]
D --> A["Avoidance<br/>check each request; only grant<br/>if the system stays safe (banker's)"]
D --> DR["Detection and recovery<br/>let it happen, find cycles,<br/>kill or roll back a thread"]
D --> I["Ignore it<br/>(ostrich approach)<br/>rare enough; reboot / restart"]
| Strategy | Cost | Used in |
|---|---|---|
| Prevention | Restricts how programs use resources | Lock ordering in kernels and applications |
| Avoidance | Needs each thread's maximum needs in advance; check on every request | Textbooks, some embedded or real-time systems |
| Detection and recovery | Periodic cycle search; victims lose work | Databases (abort a transaction) |
| Ignore | None, until it happens | Most general-purpose OSes for application locks |
Avoidance: The Banker's Algorithm
The idea: grant a request only if, afterwards, there is still some order in which every thread can get its maximum needs and finish. Such an order is a safe sequence, and the state is safe.
flowchart TD
S["Work = Available<br/>Finish[i] = false for all"] --> F{"Find i with Finish[i] = false<br/>and Need[i] ≤ Work"}
F -->|"found"| U["Work = Work + Allocation[i]<br/>Finish[i] = true<br/>(i finishes and returns its resources)"]
U --> F
F -->|"none"| C{"All Finish = true?"}
C -->|"yes"| SAFE["Safe state"]
C -->|"no"| UNSAFE["Unsafe state"]
Unsafe does not mean deadlocked; it means deadlock might happen, so the request is refused for now.
Worked Example
Five processes, three resource types A, B, C (10, 5 and 7 instances in total).
| Process | Allocation (A B C) | Max (A B C) | Need = Max − Allocation |
|---|---|---|---|
| P0 | 0 1 0 | 7 5 3 | 7 4 3 |
| P1 | 2 0 0 | 3 2 2 | 1 2 2 |
| P2 | 3 0 2 | 9 0 2 | 6 0 0 |
| P3 | 2 1 1 | 2 2 2 | 0 1 1 |
| P4 | 0 0 2 | 4 3 3 | 4 3 1 |
Available = (3 3 2).
Is the state safe? Repeatedly pick a process whose Need fits in Work:
| Step | Pick | Need ≤ Work? | Work after it finishes |
|---|---|---|---|
| start | 3 3 2 | ||
| 1 | P1 | 1 2 2 ≤ 3 3 2 ✔ | 5 3 2 |
| 2 | P3 | 0 1 1 ≤ 5 3 2 ✔ | 7 4 3 |
| 3 | P4 | 4 3 1 ≤ 7 4 3 ✔ | 7 4 5 |
| 4 | P0 | 7 4 3 ≤ 7 4 5 ✔ | 7 5 5 |
| 5 | P2 | 6 0 0 ≤ 7 5 5 ✔ | 10 5 7 |
All finish, so the state is safe with sequence P1, P3, P4, P0, P2. Other safe sequences also exist; any one is enough.
P1 requests (1 0 2). Request ≤ Need (1 2 2) ✔ and ≤ Available (3 3 2) ✔. Pretend to grant it: Available becomes (2 3 0), P1's Allocation (3 0 2), Need (0 2 0). Re-running the check finds the same safe sequence P1, P3, P4, P0, P2, so the request is granted.
Then P0 requests (0 2 0). It fits in Available (2 3 0). Pretend to grant it: Available becomes (2 1 0) and P0's Need (7 2 3). Now no process's Need fits in (2 1 0): P1 needs (0 2 0), P3 needs (0 1 1), and the others need more. The state is unsafe, so P0 must wait, even though the resources are free.
Sources: Wikipedia: Banker's algorithm
Detection and Recovery
With single-instance resources, keep a wait-for graph (thread → thread it is waiting on) and look for a cycle. With multiple instances, run a banker's-style check using current requests instead of maximum needs.
Recovery options: kill one or more threads in the cycle, or preempt a resource and roll its owner back to a checkpoint. Choose a victim that has done the least work or holds the most resources.
Livelock, Starvation and Priority Inversion
| Problem | What happens | Example | Fix |
|---|---|---|---|
| Deadlock | Everyone waits; nothing runs | Two locks, opposite order | Lock ordering |
| Livelock | Everyone keeps running but makes no progress | Two people in a corridor both stepping aside the same way, again and again; threads that trylock, fail, release, retry in sync | Random back-off |
| Starvation | Some thread never gets the resource, while others progress | Low priority never scheduled; writers starved by readers | Aging, fair queues |
| Priority inversion | A high-priority thread waits for a lock held by a low-priority one, while a medium-priority thread keeps the low one off the CPU | Mars Pathfinder, 1997 | Priority inheritance: the lock holder temporarily gets the waiter's priority |
sequenceDiagram
participant L as Low priority
participant M as Medium priority
participant H as High priority
L->>L: acquires lock
H->>H: wakes, needs lock: blocks
M->>M: wakes, runs (beats L)
Note over L,H: H waits for L, L waits for M: H effectively has lowest priority
Note over L: with priority inheritance, L runs at H's priority,<br/>releases the lock, H continues
Sources: Wikipedia: Priority inversion
Common Traps
- All four conditions are needed; a cycle alone is not enough with multi-instance resources.
- Unsafe ≠ deadlocked.
- In the banker's algorithm, first check Request ≤ Need (otherwise it is an error) and Request ≤ Available (otherwise wait).
- Deadlock is permanent waiting; starvation is indefinite but not necessarily permanent.
Interview Questions
- What are the necessary conditions for deadlock? Mutual exclusion, hold and wait, no preemption, circular wait, all at the same time.
- How do you prevent deadlock in practice? Acquire locks in a fixed global order; or use
trylockwith back-off; or hold at most one lock at a time. - Deadlock vs starvation vs livelock? Deadlock: everyone blocked forever. Starvation: one thread is never served while others run. Livelock: threads keep acting but make no progress.
- What does the banker's algorithm do? Before granting a request it simulates whether all processes could still finish in some order using their declared maximums; if not, the request waits.
- Why is the banker's algorithm rarely used in general-purpose OSes? Processes rarely know their maximum needs, the number of processes changes, and the check on every request is costly.
- What is priority inversion and how is it fixed? A high-priority task waits on a lock held by a low-priority task that is preempted by medium-priority work. Fix with priority inheritance or priority ceiling.
Key Points
- Deadlock needs mutual exclusion, hold and wait, no preemption and circular wait; break one to prevent it.
- The banker's algorithm grants requests only when a safe sequence still exists.
- Know the differences between deadlock, livelock, starvation and priority inversion.
Memory Management
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Memory paging
- Wikipedia: Memory segmentation
- Wikipedia: Page table
- Wikipedia: Translation lookaside buffer
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 9
Many processes share one physical memory, but each one should see its own private memory starting at address 0, and none should be able to touch another's. The OS and the hardware memory management unit (MMU) achieve this by translating every address a program uses (a virtual or logical address) into a physical address in RAM. This page explains how that translation works.
> Numbers and addresses on this page are illustrative; the worked arithmetic was checked with a short script.
Purpose and Scope
This page covers logical versus physical addresses, contiguous allocation and fragmentation, paging, page tables (single-level, multi-level, inverted), the TLB with an effective-access-time calculation, and segmentation. Paging to disk, page faults and replacement are on Virtual Memory.
The Apartment Building Analogy
| Building | Memory |
|---|---|
| Each tenant calls their rooms "room 1, room 2, ..." | Each process uses its own virtual addresses from 0 |
| The building manager's list: "tenant A's room 1 is flat 37" | The page table |
| Rooms are all the same size | Pages and frames are all the same size |
| A tenant can't open a door that isn't on their list | Memory protection |
| The manager remembers the last few lookups | The TLB |
Logical and Physical Addresses
flowchart LR
CPU["CPU issues<br/>virtual address"] --> MMU["MMU<br/>(TLB + page table walk)"]
MMU -->|"physical address"| RAM["RAM"]
MMU -->|"not allowed / not present"| F["Fault to the kernel"]
| Logical (virtual) address | Physical address | |
|---|---|---|
| Seen by | The program | The memory chips |
| Range | Same for every process (e.g. 0 to 2⁴⁸) | Size of installed RAM |
| Translated by | The MMU, on every access |
Contiguous Allocation and Fragmentation
The simplest scheme gives each process one contiguous block of physical memory, using a base register (where it starts) and a limit register (how big it is).
When processes come and go, free memory becomes scattered holes:
flowchart LR
A["P1<br/>100 KB"] --- H1["free 30 KB"] --- B["P2<br/>200 KB"] --- H2["free 50 KB"] --- C["P3<br/>80 KB"] --- H3["free 40 KB"]
A new 100 KB process cannot fit, even though 120 KB is free in total.
| Kind | What is wasted | Caused by | Fix |
|---|---|---|---|
| External fragmentation | Free memory split into holes too small to use | Variable-size allocation | Compaction (move processes), or paging |
| Internal fragmentation | Unused space inside an allocated block | Fixed-size allocation units | Smaller units |
| Placement rule | Picks | Note |
|---|---|---|
| First fit | The first hole big enough | Fast |
| Best fit | The smallest hole big enough | Leaves tiny useless holes |
| Worst fit | The largest hole | Leaves big holes, usually worse overall |
Paging
Paging removes external fragmentation by cutting both spaces into equal fixed-size pieces:
- virtual memory into pages,
- physical memory into frames (same size, commonly 4 KB),
and allowing any page to go in any frame. A process's pages need not be next to each other in RAM.
flowchart LR
subgraph V["Process virtual pages"]
v0["page 0"]
v1["page 1"]
v2["page 2"]
v3["page 3"]
end
subgraph PT["Page table"]
t0["0 → frame 5"]
t1["1 → frame 2"]
t2["2 → not present"]
t3["3 → frame 7"]
end
subgraph P["Physical frames"]
f2["frame 2"]
f5["frame 5"]
f7["frame 7"]
end
v0 --> t0 --> f5
v1 --> t1 --> f2
v3 --> t3 --> f7
Paging has no external fragmentation, but on average wastes half a page per region at the end (internal fragmentation).
Address Translation
A virtual address splits into a page number and an offset. With page size 2ᵏ bytes, the offset is the low k bits.
flowchart LR
VA["Virtual address"] --> PN["Page number<br/>(high bits)"]
VA --> OF["Offset<br/>(low k bits)"]
PN --> PT["Page table lookup"] --> FN["Frame number"]
FN --> PA["Physical address =<br/>frame number × page size + offset"]
OF --> PA
Worked example. Page size 4 KB = 4096 = 2¹², so the offset is the low 12 bits (3 hex digits).
| Step | Value |
|---|---|
| Virtual address | 0x3A7F |
Page number = 0x3A7F >> 12 | 3 |
Offset = 0x3A7F & 0xFFF | 0xA7F |
| Page table says page 3 → frame 7 | 7 |
Physical address = 7 × 4096 + 0xA7F | 0x7A7F |
Page Table Entries
| Bit or field | Meaning |
|---|---|
| Frame number | Where the page is in RAM |
| Valid / present | Is the page in memory? If not, a page fault (Virtual Memory) |
| Read / write / execute | Protection: a write to a read-only page faults |
| User / kernel | Can user mode access it? |
| Dirty | Written since loaded; must be saved before eviction |
| Accessed (referenced) | Used recently; helps replacement |
Sources: Wikipedia: Memory paging
Page Table Size and Multi-Level Tables
A flat table needs one entry per virtual page:
32-bit addresses, 4 KB pages: 2^32 / 2^12 = 2^20 entries
× 4 bytes per entry = 4 MB per process
That is wasteful because most of the address space is unused. A multi-level (hierarchical) page table only builds the lower levels where memory is actually used.
flowchart LR
VA["Virtual address:<br/>L1 index | L2 index | offset"] --> R["Table base register<br/>(Arm TTBR, x86 CR3)"]
R --> L1["Level-1 table"]
L1 -->|"L1 index"| L2["Level-2 table<br/>(only exists if used)"]
L2 -->|"L2 index"| F["Frame number"]
F --> PA["+ offset = physical address"]
64-bit systems typically use 4 levels (48-bit addresses with 4 KB pages: 9 + 9 + 9 + 9 index bits + 12 offset bits). The cost is one memory access per level on every translation, which is why the TLB is essential.
| Type | Idea | Trade-off |
|---|---|---|
| Flat | One big array | Simple; huge for large address spaces |
| Multi-level | Tree of tables | Small for sparse address spaces; several memory accesses per walk |
| Hashed | Hash of page number → entry | Good for very large sparse spaces |
| Inverted | One entry per physical frame, holding (process, page) | Size depends on RAM, not address space; lookup needs a search or hash |
Sources: Wikipedia: Page table
The TLB
The translation lookaside buffer is a small, fast cache of recent page-to-frame translations inside the MMU.
flowchart TD
VA["Virtual address"] --> T{"In TLB?"}
T -->|"hit (most accesses)"| PA["Physical address, no extra memory access"]
T -->|"miss"| W["Walk the page table in memory"]
W --> V{"Entry valid?"}
V -->|"yes"| U["Put translation in TLB"] --> PA
V -->|"no"| PF["Page fault → kernel"]
Effective Access Time
With a single-level page table, a TLB miss costs one extra memory access.
EAT = hit ratio × (TLB time + memory time) + miss ratio × (TLB time + 2 × memory time)
Memory access 100 ns, TLB hit ratio 90%:
| TLB lookup time | EAT |
|---|---|
| Ignored (0 ns) | 0.9 × 100 + 0.1 × 200 = 110 ns |
| 20 ns | 0.9 × 120 + 0.1 × 220 = 130 ns |
Without any TLB every access would cost 200 ns, so even a small TLB nearly halves the cost.
TLBs and Context Switches
Different processes use the same virtual addresses for different data. On a switch the OS must either flush the TLB or tag each entry with an address-space ID (ASID on Arm, PCID on x86) so entries from different processes can coexist. Threads in the same process share the address space, so their switches keep the TLB.
Sources: Wikipedia: Translation lookaside buffer
Segmentation
Segmentation divides memory by meaning instead of fixed size: a code segment, a data segment, a stack segment, each with its own base, limit and permissions. An address is (segment, offset).
| Paging | Segmentation | |
|---|---|---|
| Unit | Fixed-size page | Variable-size segment |
| Visible to the programmer | No | Yes (logical divisions) |
| External fragmentation | No | Yes |
| Internal fragmentation | Yes, a little | No |
| Used today | Everywhere | Mostly historical; x86-64 keeps it only in vestigial form |
Sources: Wikipedia: Memory segmentation
Common Traps
- Paging removes external fragmentation but not internal.
- Physical address = frame × page size + offset; the offset is never translated.
- A TLB miss is not a page fault: a miss means "walk the table"; a fault means "the page is not present or not allowed".
- Page table size depends on the virtual address space; inverted tables depend on physical memory.
Interview Questions
- Why do we need virtual memory addresses? Isolation (each process has its own space), relocation (load anywhere), and the ability to use more memory than RAM.
- Internal vs external fragmentation? Internal: unused space inside an allocated block. External: free memory split into holes too small to use.
- How is a virtual address translated with paging? Split into page number and offset; look up the page number in the page table (or TLB) to get the frame; physical address = frame × page size + offset.
- Why multi-level page tables? A flat table for a large, sparse address space is huge; multi-level tables only allocate the parts in use.
- What is a TLB and why does it matter? A cache of recent translations; without it every memory access would need extra accesses to walk the page table.
- Compute: 4 KB pages, address 0x3A7F, page 3 maps to frame 7. Physical 0x7A7F.
Key Points
- The MMU translates virtual to physical addresses on every access, giving isolation and relocation.
- Paging uses fixed-size pages and frames, avoiding external fragmentation; page tables can be multi-level.
- The TLB caches translations; EAT = hit × (TLB + mem) + miss × (TLB + 2 × mem) for one level.
Virtual Memory
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Virtual memory
- Wikipedia: Page replacement algorithm
- Wikipedia: Bélády's anomaly
- Wikipedia: Thrashing (computer science)
- Wikipedia: Copy-on-write
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 10
Virtual memory lets a process use more memory than the machine has RAM. Only the pages a process is actually using need to be in RAM; the rest can stay on disk and are brought in when first touched. When RAM fills up, the OS chooses a page to push out. Page-fault counting with FIFO, LRU and optimal replacement is one of the most common OS interview problems.
> All page-fault counts on this page were computed with a short script and the step tables were checked against it.
Purpose and Scope
This page covers demand paging, what happens on a page fault, effective access time with faults, the replacement algorithms (FIFO, optimal, LRU, clock) with worked traces, Bélády's anomaly, thrashing and the working set, and copy-on-write and memory-mapped files. Address translation and the TLB are on Memory Management.
The Desk and Bookshelf Analogy
| Study | Virtual memory |
|---|---|
| Your desk holds 3 books | RAM holds a few frames |
| The bookshelf holds all your books | Disk (swap or the program file) |
| Fetching a book from the shelf | A page fault |
| Desk full: put one book back to make room | Page replacement |
| Which book to put back? | FIFO, LRU, optimal, clock |
| Constantly swapping books, never reading | Thrashing |
Demand Paging
Pages are loaded only when a program first touches them. A page not in RAM has its valid/present bit clear in the page table.
sequenceDiagram
participant P as Process
participant M as MMU
participant K as Kernel
participant D as Disk
P->>M: access address in page 5
M-->>K: page fault (present bit = 0)
K->>K: is the address legal? if not: segmentation fault
K->>K: find a free frame (or evict a victim)
K->>D: read page 5 into the frame
Note over K,D: process blocked; another runs meanwhile
D-->>K: read done
K->>K: update page table: present, frame number
K->>P: restart the faulting instruction
| Kind of fault | Meaning | Cost |
|---|---|---|
| Minor (soft) | The page is already in RAM (e.g. shared library, page cache); just map it | Microseconds |
| Major (hard) | Must read from disk | Milliseconds on HDD; tens to hundreds of µs on SSD |
| Invalid | Address not part of the process at all | The process gets SIGSEGV |
Sources: Wikipedia: Virtual memory
Effective Access Time with Page Faults
EAT = (1 − p) × memory access time + p × page-fault service time
Memory access 100 ns, fault service 8 ms (8,000,000 ns), fault rate p = 1/1000:
EAT = 0.999 × 100 + 0.001 × 8,000,000 = 99.9 + 8,000 ≈ 8,100 ns
One fault per thousand accesses makes memory about 80 times slower. To keep the slowdown under 10% (EAT ≤ 110 ns) the fault rate must be below about 1 in 800,000. That is why good replacement matters so much.
Page Replacement
When a fault needs a frame and none is free, a victim page is chosen. If it is dirty it must first be written back to disk.
flowchart TD
F["Page fault"] --> Q{"Free frame?"}
Q -->|"yes"| L["Load page into it"]
Q -->|"no"| V["Choose victim (replacement algorithm)"]
V --> D{"Victim dirty?"}
D -->|"yes"| W["Write victim to disk"] --> L
D -->|"no"| L
L --> U["Update page tables, restart instruction"]
| Algorithm | Evicts | Notes |
|---|---|---|
| FIFO | The page loaded longest ago | Simple; ignores use; suffers Bélády's anomaly |
| Optimal (OPT / Bélády's MIN) | The page that will not be used for the longest time in the future | Fewest possible faults; needs the future, so only a benchmark |
| LRU | The page not used for the longest time in the past | Close to optimal in practice; exact LRU is expensive in hardware |
| Clock (second chance) | Sweeps frames like a clock hand; a page with its accessed bit set gets the bit cleared and a second chance | Cheap LRU approximation used by real kernels |
| LFU / MFU | Least / most frequently used | Rarely good on their own |
Worked Example
Reference string (12 references), 3 frames, all empty at the start:
7 0 1 2 0 3 0 4 2 3 0 3
In the tables, F marks a fault; the frame column shows the three frames' contents after each reference.
FIFO: 10 faults
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Frames | 7 | 7 0 | 7 0 1 | 2 0 1 | 2 0 1 | 2 3 1 | 2 3 0 | 4 3 0 | 4 2 0 | 4 2 3 | 0 2 3 | 0 2 3 |
| Fault | F | F | F | F | F | F | F | F | F | F |
LRU: 9 faults
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Frames | 7 | 7 0 | 7 0 1 | 2 0 1 | 2 0 1 | 2 0 3 | 2 0 3 | 4 0 3 | 4 0 2 | 4 3 2 | 0 3 2 | 0 3 2 |
| Fault | F | F | F | F | F | F | F | F | F |
Optimal: 7 faults
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Frames | 7 | 7 0 | 7 0 1 | 2 0 1 | 2 0 1 | 2 0 3 | 2 0 3 | 2 4 3 | 2 4 3 | 2 4 3 | 0 4 3 | 0 4 3 |
| Fault | F | F | F | F | F | F | F |
How to choose the victim at the reference to 3 (time 6, frames 2 0 1):
| Algorithm | Reasoning | Evicts |
|---|---|---|
| FIFO | 2 was loaded most recently, 0 and 1 earlier; 0 was loaded first | 0 |
| LRU | Last used: 2 at time 4, 0 at time 5, 1 at time 3 | 1 |
| OPT | Next use: 0 at time 7, 2 at time 9, 1 never in this string | 1 |
The full classic 20-reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 gives:
| Frames | FIFO | LRU | OPT |
|---|---|---|---|
| 3 | 15 | 12 | 9 |
| 4 | 10 | 8 | 8 |
Sources: Wikipedia: Page replacement algorithm
The Clock Algorithm
flowchart TD
H["Look at frame under the hand"] --> A{"Accessed bit = 1?"}
A -->|"yes"| C["Clear it to 0 (second chance)<br/>advance hand"] --> H
A -->|"no"| E["Evict this page<br/>load new page here, advance hand"]
Hardware sets the accessed bit on every use, so the kernel gets an approximate "used recently" signal for free.
Bélády's Anomaly
Normally more frames mean fewer faults. With FIFO that is not guaranteed:
Reference string 1 2 3 4 1 2 5 1 2 3 4 5 |
FIFO faults |
|---|---|
| 3 frames | 9 |
| 4 frames | 10 |
LRU and OPT never show this: they are stack algorithms, where the pages kept with n frames are always a subset of those kept with n + 1.
Sources: Wikipedia: Bélády's anomaly
Thrashing and the Working Set
If the processes together need more pages than there are frames, nearly every access faults; the system spends its time moving pages and CPU utilisation collapses. This is thrashing.
flowchart LR
A["More processes"] --> B["Fewer frames each"] --> C["More page faults"] --> D["CPU idle waiting for disk"]
D --> E["Naive scheduler sees low CPU use,<br/>admits even more processes"] --> A
The working set of a process is the set of pages it used in the last Δ references. If the sum of all working sets exceeds RAM, thrashing follows.
| Remedy | How |
|---|---|
| Working-set model | Keep each process's working set resident; suspend a process if they don't all fit |
| Page-fault-frequency control | Give more frames to processes faulting a lot, take frames from those faulting little |
| Reduce load | Swap out whole processes, or kill one (Linux OOM killer) |
| Add RAM | The real fix |
Sources: Wikipedia: Thrashing (computer science)
Copy-on-Write
After fork, parent and child would each need a full copy of memory, but the child usually calls exec almost at once. Copy-on-write (COW) shares the pages, marked read-only, and copies a page only when one side writes to it.
flowchart TD
F["fork()"] --> S["Parent and child page tables point to<br/>the same frames, all marked read-only"]
S --> W{"Someone writes a page"}
W --> PF["Protection fault"]
PF --> C["Kernel copies just that page,<br/>gives the writer its own writable copy"]
This makes fork fast and is why counting fork calls says nothing about memory use. (Processes)
Sources: Wikipedia: Copy-on-write
Memory-Mapped Files
mmap maps a file into the address space. Reading the memory faults pages in from the file, and dirty pages are written back to it. The same mechanism loads program code and shared libraries, and lets several processes share one physical copy of a library.
Common Traps
- OPT needs the future; use it only to compare other algorithms.
- On a tie, state your rule; with FIFO the victim is by load time, not last use.
- A page hit under FIFO does not change the queue order; under LRU it does.
- Bélády's anomaly affects FIFO, not LRU or OPT.
- More processes do not mean more throughput once the working sets exceed RAM.
Interview Questions
- What is a page fault, step by step? The MMU finds the present bit clear and traps to the kernel; the kernel checks the address is valid, finds or frees a frame, reads the page from disk, updates the page table and restarts the instruction.
- FIFO vs LRU vs OPT? FIFO evicts the oldest loaded page, LRU the least recently used, OPT the one used furthest in the future. OPT is the lower bound; LRU is usually close.
- What is Bélády's anomaly? More frames causing more faults, possible with FIFO; e.g.
1 2 3 4 1 2 5 1 2 3 4 5gives 9 faults with 3 frames and 10 with 4. - What is thrashing and how do you stop it? Constant paging because working sets exceed RAM; reduce the degree of multiprogramming, use working-set or fault-frequency control, or add memory.
- How does copy-on-write make
forkcheap? Pages are shared read-only and copied only when written. - Why is LRU approximated rather than implemented exactly? Exact LRU needs an update on every memory access; the clock algorithm uses the hardware accessed bit instead.
Key Points
- Demand paging loads pages on first use; a fault costs milliseconds, so fault rates must be tiny.
- FIFO, LRU and OPT give different fault counts; OPT is the minimum and LRU approximates it; FIFO can show Bélády's anomaly.
- Thrashing happens when working sets exceed RAM; copy-on-write and
mmapreuse the same paging machinery.
Files, Storage and I/O
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: File system
- Wikipedia: Inode
- Wikipedia: Journaling file system
- Wikipedia: I/O scheduling
- Wikipedia: Interrupt
- Wikipedia: Direct memory access
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapters 11-14
A file system turns a disk, which is just a long row of numbered blocks, into named files and folders with permissions. Underneath, the OS talks to devices using interrupts and DMA, and decides the order in which disk requests are served. Interviews ask about inodes, hard versus soft links, journaling, file descriptors, disk scheduling and polling versus interrupts.
> All disk-scheduling totals on this page were computed with a short script.
Purpose and Scope
This page covers files and file descriptors, directories and inodes, hard and symbolic links, block allocation, journaling, the page cache, disk scheduling (FCFS, SSTF, SCAN, LOOK, C-SCAN, C-LOOK) with a worked example, and I/O methods (polling, interrupts, DMA). System calls are on Kernel and System Calls.
The Library Catalogue Analogy
| Library | File system |
|---|---|
| Shelves of numbered slots | Disk blocks |
| A catalogue card: author, size, which slots hold the book | An inode |
| The alphabetical index: title → card number | A directory: name → inode number |
| Two index entries pointing to the same card | A hard link |
| A note saying "see the entry for X" | A symbolic link |
| A librarian's log of changes in progress | A journal |
Files and File Descriptors
To a program a file is a sequence of bytes. It opens a file and gets back a small integer, the file descriptor (fd).
// illustrative
int fd = open("notes.txt", O_RDONLY); // e.g. returns 3
char buf[100];
ssize_t n = read(fd, buf, sizeof buf); // read up to 100 bytes
close(fd);
flowchart LR
subgraph P["Process"]
FD["fd table<br/>0 stdin, 1 stdout, 2 stderr, 3 →"]
end
FD -->|"3"| OF["Open-file entry<br/>current offset, mode"]
OF --> IN["Inode<br/>size, owner, block pointers"]
IN --> B["Data blocks on disk"]
Three levels: the per-process fd table, a system-wide open-file table (holding the current read/write offset), and the inode. After fork, parent and child share the same open-file entries, so they share the file offset.
Inodes and Directories
On Unix-like file systems each file has an inode holding everything about it except its name:
| In the inode | Not in the inode |
|---|---|
| Type, permissions, owner, size, timestamps | The file name |
| Link count | |
| Pointers to the data blocks |
A directory is a special file that maps names to inode numbers. Looking up /home/ana/notes.txt reads the root directory, finds home, reads that directory, finds ana, and so on.
flowchart LR
R["/ (inode 2)"] -->|"home"| H["home (inode 11)"]
H -->|"ana"| A["ana (inode 340)"]
A -->|"notes.txt"| N["inode 812<br/>size, owner, blocks"]
N --> D["data blocks"]
Block Pointers in a Classic Inode
flowchart LR
I["Inode"] --> D1["12 direct pointers → data blocks"]
I --> S["single indirect → block of pointers → data"]
I --> DB["double indirect → pointers → pointers → data"]
I --> T["triple indirect → three levels → data"]
Small files need only direct pointers (fast); big files use the indirect levels. Modern file systems such as ext4 use extents instead: (start block, length) runs.
Sources: Wikipedia: Inode, Wikipedia: File system
Hard Links and Symbolic Links
| Hard link | Symbolic (soft) link | |
|---|---|---|
| What it is | Another directory entry for the same inode | A small file containing a path |
| Command | ln a b | ln -s a b |
| Delete the original name | File still exists (link count > 0) | Link becomes dangling |
| Across file systems | No | Yes |
| To a directory | Usually not allowed | Yes |
flowchart TD
subgraph Hard["Hard link"]
n1["name: a"] --> i1["inode 812 (links = 2)"]
n2["name: b"] --> i1
end
subgraph Soft["Symbolic link"]
s1["name: c (inode 900)<br/>contents: 'a'"] -.->|"path lookup"| n3["name: a"] --> i2["inode 812"]
end
A file's data is freed only when its link count reaches 0 and no process still has it open.
Allocating Blocks
| Method | Idea | Good | Bad |
|---|---|---|---|
| Contiguous | Each file in one run of blocks | Fast sequential and random access | External fragmentation; hard to grow |
| Linked | Each block points to the next (FAT keeps the chain in a table) | No fragmentation | Slow random access |
| Indexed | An index block (or inode) lists all blocks | Fast random access | Index overhead |
| Extents | List of (start, length) runs | Compact, fast | More complex |
Free space is tracked with a bitmap (one bit per block) or a free list.
Journaling and Crash Consistency
Creating a file touches several blocks: the inode, the directory, the free-space bitmap. If power fails halfway, the file system can be left inconsistent.
sequenceDiagram
participant FS as File system
participant J as Journal (log)
participant D as Main disk area
FS->>J: 1. write intended changes
FS->>J: 2. write "commit" record
FS->>D: 3. apply changes in place (checkpoint)
FS->>J: 4. mark transaction done
Note over FS,D: crash before 2: ignore it. Crash after 2: replay from journal
| Journal mode (ext4 names) | What is logged | Trade-off |
|---|---|---|
journal | Metadata and data | Safest, slowest |
ordered (default) | Metadata only; data written before its metadata commits | Good balance |
writeback | Metadata only, no ordering | Fastest; files may contain stale data after a crash |
Without a journal, recovery needs a full scan (fsck). Copy-on-write file systems (btrfs, ZFS) avoid in-place updates altogether.
Sources: Wikipedia: Journaling file system
The Page Cache
The kernel keeps recently used file data in otherwise free RAM. read often copies from RAM without touching the disk; write usually just updates the cache and marks pages dirty, and they are written back later. fsync(fd) forces them to disk. That is why a crash can lose data that write already "returned" for.
Disk Scheduling
For a hard disk the slow part is moving the head (seek). The OS reorders pending requests to cut total head movement.
Worked example. Cylinders 0-199, head at 53, pending requests:
98, 183, 37, 122, 14, 124, 65, 67
| Algorithm | Rule | Order served | Total head movement |
|---|---|---|---|
| FCFS | In arrival order | 98, 183, 37, 122, 14, 124, 65, 67 | 640 |
| SSTF | Nearest request next | 65, 67, 37, 14, 98, 122, 124, 183 | 236 |
| SCAN (elevator), moving toward 0 | Sweep to the end of the disk, then reverse | 37, 14, (0), 65, 67, 98, 122, 124, 183 | 236 |
| LOOK, moving toward 0 | Like SCAN but turn at the last request | 37, 14, 65, 67, 98, 122, 124, 183 | 208 |
| C-SCAN, moving toward 199 | Sweep up to the end, jump to 0, sweep up again | 65, 67, 98, 122, 124, 183, (199), (0), 14, 37 | 382 counting the 199 → 0 return; 183 if the return is not counted |
| C-LOOK, moving toward 199 | Up to the last request, jump to the lowest request | 65, 67, 98, 122, 124, 183, 14, 37 | 322 counting the jump |
flowchart LR
S["head 53"] --> A["37"] --> B["14"] --> C["turn at 14"] --> D["65"] --> E["67"] --> F["98"] --> G["122"] --> H["124"] --> I["183"]
(The diagram shows LOOK: 53 − 14 = 39, then 183 − 14 = 169, total 208.)
| Algorithm | Pros | Cons |
|---|---|---|
| FCFS | Fair | Lots of movement |
| SSTF | Low movement | Can starve far requests |
| SCAN / LOOK | No starvation, low movement | Middle cylinders get better service |
| C-SCAN / C-LOOK | More uniform waiting time | Return sweep costs movement |
SSDs have no head, so modern Linux uses simple or deadline-based I/O schedulers (none, mq-deadline, bfq) that focus on merging and fairness instead.
Trap: always state the starting direction, whether SCAN goes to the physical end, and whether you count the C-SCAN return jump; answers differ by convention.
Sources: Wikipedia: I/O scheduling
How the OS Talks to Devices
flowchart TD
Q["How does the CPU learn the device is ready?"] --> PO["Polling<br/>CPU keeps checking a status register"]
Q --> IN["Interrupts<br/>device signals the CPU when done"]
IN --> DMA["DMA<br/>device copies the data to memory itself,<br/>interrupts once at the end"]
| Method | CPU work | Best for |
|---|---|---|
| Polling (busy waiting) | CPU loops checking status | Very fast devices or very short waits (high-speed NICs and NVMe can poll) |
| Interrupt-driven | CPU does other work; handler runs when the device interrupts | Slow or unpredictable devices (keyboard, network) |
| DMA | CPU only sets up the transfer; the DMA engine moves the data | Large transfers (disk, network buffers) |
Interrupt Handling
sequenceDiagram
participant D as Device
participant C as CPU
participant K as Kernel
D->>C: interrupt line raised
C->>K: finish current instruction, save state, jump to handler
K->>K: top half: acknowledge device, grab data quickly
K->>K: schedule bottom half (softirq / work queue) for slower work
K->>C: restore state, return to interrupted code
Handlers are split in two because interrupts must be handled fast; slow work is deferred.
Sources: Wikipedia: Interrupt, Wikipedia: Direct memory access
Common Traps
- The file name is in the directory, not the inode.
- Deleting a file (
unlink) removes a name; the data stays while other links or open fds exist. writereturning does not mean the data is on disk; usefsync.- Disk scheduling answers depend on direction and end-of-disk conventions; say which you use.
Interview Questions
- What is an inode? A structure holding a file's metadata (type, permissions, owner, size, timestamps, link count) and the locations of its data blocks, but not its name.
- Hard link vs soft link? A hard link is another name for the same inode; a soft link is a file containing a path, which can dangle or cross file systems.
- What does journaling do? Writes intended metadata changes to a log and commits them before applying in place, so after a crash the file system can replay or discard incomplete operations instead of running a full check.
- What is a file descriptor? A per-process integer index into the open-file table; 0, 1 and 2 are stdin, stdout and stderr.
- Solve SSTF for head 53 and requests 98, 183, 37, 122, 14, 124, 65, 67. Order 65, 67, 37, 14, 98, 122, 124, 183; total 236.
- Polling vs interrupts vs DMA? Polling wastes CPU but has low latency; interrupts free the CPU until the device is ready; DMA lets the device move data itself with one interrupt at the end.
Key Points
- Directories map names to inodes; inodes hold metadata and block pointers; hard links share an inode, soft links store a path.
- Journaling makes multi-block updates crash-safe; the page cache delays writes until
fsyncor write-back. - Disk schedulers (SSTF, SCAN, LOOK, C-SCAN) cut seek distance; devices are driven by polling, interrupts and DMA.
Kernel and System Calls
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Kernel (operating system)
- Wikipedia: System call
- Wikipedia: Protection ring
- Wikipedia: Microkernel
- Wikipedia: Monolithic kernel
- Wikipedia: Interrupt
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 2
The kernel is the part of the OS that runs with full hardware privilege. Programs cannot call it like an ordinary function; they must cross a hardware-enforced boundary using a system call. This page explains how that crossing works, the three ways the CPU enters the kernel, how kernels are structured, and what happens when the machine boots. It finishes with the classic interview trace: "what happens when you type ls and press Enter?"
> Assembly and traces on this page are illustrative.
Purpose and Scope
This page covers privilege levels, the system call path, interrupts versus traps versus exceptions, monolithic, micro- and hybrid kernels, loadable modules, the boot sequence, and an end-to-end trace. Device interrupts in detail are on Files and I/O.
The Bank Counter Analogy
| Bank | Computer |
|---|---|
| Customers in the public hall | User-mode programs |
| The vault behind the counter | Kernel memory and hardware |
| Filling in a form and handing it through the window | A system call |
| The teller checks the form before acting | The kernel validates arguments |
| The fire alarm interrupts everyone | A hardware interrupt |
| A customer faints: staff must respond | An exception (fault) |
Privilege Levels
flowchart TB
subgraph Arm["Arm A-profile exception levels"]
EL0["EL0: applications"]
EL1["EL1: OS kernel"]
EL2["EL2: hypervisor"]
EL3["EL3: secure monitor / firmware"]
end
subgraph X86["x86 protection rings"]
R3["Ring 3: applications"]
R0["Ring 0: kernel"]
end
User code that tries a privileged instruction (change the page table base, disable interrupts) causes an exception, and the kernel usually kills the program.
Sources: Wikipedia: Protection ring
The System Call Path
// illustrative: what a program writes
write(1, "hi\n", 3);
sequenceDiagram
participant A as Application (user mode)
participant L as libc wrapper
participant C as CPU
participant K as Kernel (kernel mode)
A->>L: write(1, "hi\n", 3)
L->>L: put syscall number and arguments in registers
L->>C: SVC #0 (Arm) / syscall (x86-64)
C->>K: switch to kernel mode, jump to the fixed entry point
K->>K: save user registers, look up syscall table[number]
K->>K: sys_write: check fd, copy data from user memory safely
K-->>C: put return value in a register
C-->>L: return to user mode (ERET / sysret)
L-->>A: return 3 (or -1 and set errno)
// illustrative Arm64 Linux: write(1, msg, 3)
mov x0, #1 // fd
adr x1, msg // buffer
mov x2, #3 // count
mov x8, #64 // syscall number for write on arm64 Linux
svc #0 // trap into the kernel
Key points:
- Entry is only through a fixed, kernel-chosen address; programs can't jump into arbitrary kernel code.
- The kernel must never trust user pointers; it checks them and copies with special routines (
copy_from_user). - A system call costs far more than a function call (mode switch, register saving, cache and TLB effects), so programs batch work (buffered I/O in
stdio).
| Category | Examples |
|---|---|
| Process control | fork, execve, exit, wait4, kill |
| Files | open, read, write, close, lseek, stat |
| Memory | mmap, munmap, brk |
| Communication | pipe, socket, send, recv |
| Information | getpid, clock_gettime |
Some calls such as clock_gettime are often served in user mode through the vDSO, a small kernel-provided library, without a real mode switch.
Sources: Wikipedia: System call
Three Ways into the Kernel
| Kind | Caused by | Synchronous? | Examples |
|---|---|---|---|
| Interrupt | A device or timer, outside the program | No: can arrive at any time | Timer tick, disk done, network packet |
| Trap (software interrupt) | The program on purpose | Yes | System call (SVC, syscall), breakpoint |
| Exception / fault | The program by accident | Yes | Page fault, divide by zero, illegal instruction |
flowchart TD
U["User code running"] --> I["Interrupt<br/>(device, timer)"]
U --> T["Trap<br/>(system call)"]
U --> F["Fault<br/>(page fault, bad instruction)"]
I --> V["Exception vector table<br/>in the kernel"]
T --> V
F --> V
V --> H["Handler runs in kernel mode"]
H --> R{"Outcome"}
R --> RE["Return to the same program"]
R --> SW["Schedule another thread"]
R --> KI["Kill the program (SIGSEGV, SIGILL)"]
The timer interrupt is what makes preemptive scheduling possible (CPU Scheduling).
Sources: Wikipedia: Interrupt
Kernel Designs
flowchart TB
subgraph Mono["Monolithic kernel"]
direction TB
MU["Apps"] --> MK["Kernel: scheduler, memory, file systems,<br/>drivers, network stack — all in kernel mode"]
end
subgraph Micro["Microkernel"]
direction TB
UU["Apps"] --> SV["User-mode servers:<br/>file system, drivers, network"]
SV -->|"IPC messages"| UK["Small kernel: scheduling,<br/>address spaces, IPC"]
UU -->|"IPC"| UK
end
| Monolithic | Microkernel | Hybrid | |
|---|---|---|---|
| In kernel mode | Everything | Only the minimum | Most services, some in user space |
| Speed | Fast: direct function calls | Slower: IPC for every service | In between |
| A driver crash | Can crash the whole system | Restart the server; system survives | Depends |
| Examples | Linux, traditional Unix | seL4, QNX, MINIX 3 | Windows NT, macOS XNU |
Linux is monolithic but modular: drivers can be loaded and unloaded at run time as loadable kernel modules (insmod, modprobe), still running in kernel mode.
Sources: Wikipedia: Monolithic kernel, Wikipedia: Microkernel
Booting
flowchart LR
P["Power on"] --> R["Boot ROM / firmware<br/>(UEFI or BIOS; on Arm, trusted firmware)"]
R --> B["Bootloader<br/>(GRUB, U-Boot)"]
B --> K["Kernel: set up memory, MMU,<br/>interrupts, drivers"]
K --> M["Mount root file system"]
M --> I["Start init (PID 1)<br/>(systemd)"]
I --> S["Services, login, shell"]
End-to-End Trace: Typing ls in a Shell
A favourite interview question. A good answer touches most of this wiki:
sequenceDiagram
participant KB as Keyboard
participant K as Kernel
participant SH as Shell
participant LS as ls process
KB->>K: key interrupts; driver buffers characters
K->>SH: Enter pressed: shell's blocked read() returns "ls\n"
SH->>SH: parse command, search PATH for /bin/ls
SH->>K: fork()
K-->>LS: child created (copy-on-write pages)
LS->>K: execve("/bin/ls")
K->>K: load ELF: map code, set up stack, dynamic linker loads libc
LS->>K: openat("."), getdents64(): read directory entries
K->>K: file system reads inodes/blocks (page cache or disk, DMA, interrupt)
LS->>K: write(1, names): terminal driver displays them
LS->>K: exit(0)
K->>SH: SIGCHLD; shell's waitpid() returns
SH->>K: write prompt, read() again (blocks)
| Step | Concept | Page |
|---|---|---|
| Keyboard interrupt, driver buffer | Interrupts | Files and I/O |
Shell blocked in read wakes up | Process states | Processes |
fork + execve + waitpid | Process creation | Processes |
| Child gets the CPU | Scheduling | CPU Scheduling |
| Pages loaded lazily; COW after fork | Virtual memory | Virtual Memory |
| Directory read through inodes | File systems | Files and I/O |
| Every request to the kernel | System calls | this page |
Common Traps
- A system call is not a normal function call; it changes privilege level.
- Interrupts are asynchronous; traps and faults are caused by the current instruction.
- "Monolithic" does not mean "not modular"; Linux has loadable modules.
- The kernel is not a process that runs alongside others; it runs in the context of whichever thread trapped into it (plus its own kernel threads).
Interview Questions
- What happens during a system call? The library puts the call number and arguments in registers and executes a trap instruction; the CPU switches to kernel mode at a fixed entry point; the kernel saves state, dispatches through the syscall table, validates arguments, does the work, and returns to user mode with a result.
- Interrupt vs trap vs exception? Interrupt: asynchronous, from hardware. Trap: deliberate, from an instruction (syscall). Exception/fault: accidental, from an instruction (page fault, divide by zero).
- Monolithic vs microkernel? Monolithic runs all services in kernel mode (fast, less isolated); a microkernel keeps only the essentials in the kernel and runs services in user space (more robust, more IPC overhead).
- Why can't user programs just disable interrupts? It is a privileged instruction; allowing it would let one program take over the CPU.
- What is a kernel module? Code (often a driver) loaded into a running kernel, running in kernel mode.
- What happens when you type
lsand press Enter? See the trace above: interrupt, read returns, fork, exec, file system reads, writes to the terminal, exit, wait.
Key Points
- Hardware enforces user and kernel modes; programs cross into the kernel only via system calls, interrupts and exceptions.
- System calls go through a fixed entry point and a dispatch table, with careful checking of user arguments.
- Kernels are monolithic, micro or hybrid; Linux is monolithic with loadable modules.
Interview Q&A and Glossary
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Operating system
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts
- Book: Arpaci-Dusseau and Arpaci-Dusseau, Operating Systems: Three Easy Pieces (free online)
This page is for revision just before an interview. It puts the whole wiki on one diagram, lists the most common questions with short model answers grouped by topic, gives a checklist of the worked problems to practise, and ends with a glossary.
Purpose and Scope
This page covers a one-picture summary, a quick-fire question bank, the "X vs Y" comparisons interviewers like, a problem-practice checklist and the glossary. It introduces no new ideas; each answer links to the page that explains it.
The Whole Wiki in One Picture
flowchart TD
OS["Operating system"] --> CPU["Sharing the CPU"]
OS --> MEM["Sharing memory"]
OS --> IO["Storage and devices"]
OS --> PROT["Protection"]
CPU --> PR["Processes: PCB, states, fork/exec"]
CPU --> TH["Threads: shared memory, own stack"]
CPU --> SC["Scheduling: FCFS, SJF, SRTF, RR, MLFQ"]
TH --> SY["Synchronization: mutex, semaphore, condvar"]
SY --> DL["Deadlock: 4 conditions, banker's"]
MEM --> PG["Paging, page tables, TLB"]
PG --> VM["Virtual memory: faults, FIFO/LRU/OPT,<br/>thrashing, copy-on-write"]
IO --> FS["File systems: inodes, links, journaling"]
IO --> DS["Disk scheduling, interrupts, DMA"]
PROT --> KM["User/kernel mode, system calls"]
KM --> KD["Monolithic vs microkernel"]
Quick-Fire Questions
Processes and Threads
| Question | Short answer |
|---|---|
| Process vs program? | A program is code in a file; a process is it running, with memory, registers and resources (Processes) |
| Process vs thread? | Processes have separate address spaces; threads in a process share one, each with its own stack and registers (Threads) |
| What is a PCB? | The kernel's record of a process: PID, state, registers, PC, memory info, open files |
What does fork return? | 0 in the child, the child's PID in the parent, −1 on error |
fork() called 3 times in a row: how many processes? | 8 (7 new) |
exec vs fork? | fork makes a copy; exec replaces the program in the current process (same PID) |
| Zombie vs orphan? | Zombie: finished, not yet reaped. Orphan: parent died, adopted by init |
| What is a context switch and why is it costly? | Saving one thread's state and loading another's; pure overhead plus cold caches and TLB |
| Fastest IPC? | Shared memory (but needs synchronization) |
Scheduling
| Question | Short answer |
|---|---|
| Turnaround, waiting, response? | Completion − arrival; turnaround − burst; first run − arrival (CPU Scheduling) |
| Which minimises average waiting time? | SJF (non-preemptive) / SRTF (preemptive), if bursts are known |
| Convoy effect? | Short jobs stuck behind a long one in FCFS |
| Starvation fix? | Aging |
| RR quantum too big / too small? | Becomes FCFS / too many context switches |
| How does MLFQ work? | Several priority queues; jobs that use a full quantum are demoted; periodic boost |
Synchronization and Deadlock
| Question | Short answer |
|---|---|
| Race condition? | Result depends on thread timing on shared data (Synchronization) |
| Critical section requirements? | Mutual exclusion, progress, bounded waiting |
| Mutex vs semaphore? | Mutex: owned lock for exclusion. Semaphore: counter any thread can signal |
| Spinlock vs mutex? | Spin for very short waits on multicore or where sleeping is impossible; otherwise sleep |
Why while around cond_wait? | Spurious wakeups and condition already consumed by another thread |
| Four deadlock conditions? | Mutual exclusion, hold and wait, no preemption, circular wait (Deadlock) |
| Practical deadlock prevention? | Global lock ordering |
| Safe vs unsafe state? | Safe: some order lets every process finish. Unsafe: deadlock possible (not certain) |
| Priority inversion fix? | Priority inheritance |
Memory
| Question | Short answer |
|---|---|
| Internal vs external fragmentation? | Waste inside a block / waste between blocks (Memory Management) |
| Why paging? | No external fragmentation; any page in any frame |
| Translate an address? | Split into page number and offset; frame from page table; frame × size + offset |
| What is the TLB? | Cache of page-table translations |
| TLB miss vs page fault? | Miss: walk the page table. Fault: page not present or access not allowed |
| Page fault steps? | Trap, check address, get frame (evict if needed), read from disk, update table, restart (Virtual Memory) |
| FIFO vs LRU vs OPT? | Oldest loaded / least recently used / used furthest in future (best possible) |
| Bélády's anomaly? | More frames, more faults; FIFO only |
| Thrashing? | Working sets exceed RAM; constant paging |
| Copy-on-write? | Share pages read-only after fork; copy on first write |
Files, I/O and Kernel
| Question | Short answer |
|---|---|
| What is an inode? | File metadata and block pointers, no name (Files and I/O) |
| Hard vs soft link? | Same inode / file holding a path |
| Journaling? | Log changes and commit before applying, so crashes can be recovered |
| Polling vs interrupts vs DMA? | CPU checks / device signals / device moves data itself |
| SSTF vs SCAN? | Nearest first (may starve) / elevator sweep (no starvation) |
| System call path? | Trap instruction, kernel entry, dispatch table, checks, return (Kernel and System Calls) |
| Interrupt vs trap vs fault? | Asynchronous hardware / deliberate instruction / accidental instruction |
| Monolithic vs microkernel? | All services in kernel (fast) / minimal kernel, services in user space (robust) |
Comparisons to Know Cold
flowchart LR
A["Process"] <-->|"isolation vs sharing"| B["Thread"]
C["Mutex"] <-->|"ownership vs counting"| D["Semaphore"]
E["Paging"] <-->|"fixed vs variable size"| F["Segmentation"]
G["Hard link"] <-->|"inode vs path"| H["Soft link"]
I["Monolithic"] <-->|"speed vs isolation"| J["Microkernel"]
K["Preemptive"] <-->|"can interrupt vs cannot"| L["Non-preemptive"]
Answer every "X vs Y" with three things: what each is, the key difference, and when you would choose each.
Problem-Practice Checklist
| Problem | Worked example | Check yourself |
|---|---|---|
| Scheduling Gantt chart and averages | CPU Scheduling | FCFS 8.75, SJF 7.75, SRTF 6.50, RR(q=4) 11.75 average waiting |
Count fork processes | Processes | 3 forks → 8 processes |
| Producer-consumer with semaphores | Synchronization | empty = N, full = 0, mutex = 1; counting semaphore before mutex |
| Banker's safety check | Deadlock | Safe sequence P1, P3, P4, P0, P2 |
| Address translation | Memory Management | 0x3A7F with page 3 → frame 7 gives 0x7A7F |
| TLB effective access time | Memory Management | 90% hit, 100 ns memory: 110 ns |
| Page faults FIFO / LRU / OPT | Virtual Memory | 12-ref string, 3 frames: 10 / 9 / 7 |
| Bélády's anomaly | Virtual Memory | FIFO: 9 faults with 3 frames, 10 with 4 |
| Disk scheduling totals | Files and I/O | Head 53: FCFS 640, SSTF 236, LOOK 208 |
"What happens when you run ls?" | Kernel and System Calls | Interrupt → read → fork → exec → syscalls → exit → wait |
How to Answer Well
flowchart LR
Q["Question"] --> D["Define the term<br/>in one sentence"]
D --> W["Explain how it works<br/>(draw a diagram)"]
W --> T["Give the trade-off<br/>or a trap"]
T --> E["Give a real example<br/>(Linux, Arm, a bug)"]
- Say your assumptions out loud (tie-breaking in scheduling, direction in disk scheduling, page-replacement tie rules).
- Draw: Gantt charts, state diagrams and frame tables make answers easy to follow and check.
- When writing synchronization code, explain why each lock or semaphore is there.
Glossary
| Term | Meaning | Page |
|---|---|---|
| Aging | Raising a waiting process's priority over time to prevent starvation | CPU Scheduling |
| Banker's algorithm | Deadlock avoidance: grant a request only if a safe sequence remains | Deadlock |
| Bélády's anomaly | More frames causing more page faults (FIFO) | Virtual Memory |
| Burst time | CPU time a job needs before it blocks or ends | CPU Scheduling |
| Condition variable | Lets a thread sleep until signalled, used with a mutex | Synchronization |
| Context switch | Saving one thread's CPU state and restoring another's | Processes |
| Convoy effect | Short jobs delayed behind a long one in FCFS | CPU Scheduling |
| Copy-on-write | Share pages until written, then copy | Virtual Memory |
| Critical section | Code that accesses shared data | Synchronization |
| Deadlock | Threads waiting on each other forever | Deadlock |
| Demand paging | Loading pages only when first used | Virtual Memory |
| DMA | Device transfers data to memory without the CPU | Files and I/O |
| File descriptor | Per-process integer handle for an open file | Files and I/O |
| Fragmentation | Wasted memory: internal (inside blocks) or external (between) | Memory Management |
| Inode | File metadata and block locations, without the name | Files and I/O |
| Interrupt | Asynchronous hardware signal to the CPU | Kernel and System Calls |
| IPC | Inter-process communication: pipes, sockets, shared memory, signals | Processes |
| Journaling | Logging file-system changes before applying them | Files and I/O |
| Kernel mode | Privileged CPU mode for the OS | Overview |
| Livelock | Threads active but making no progress | Deadlock |
| MLFQ | Multilevel feedback queue scheduler | CPU Scheduling |
| MMU | Hardware that translates virtual to physical addresses | Memory Management |
| Monitor | Data plus lock plus condition variables, one thread inside at a time | Synchronization |
| Mutex | Lock providing mutual exclusion, with an owner | Synchronization |
| Orphan | Process whose parent has exited | Processes |
| Page / frame | Fixed-size block of virtual / physical memory | Memory Management |
| Page fault | Trap when an accessed page is not present or not allowed | Virtual Memory |
| Page table | Map from page numbers to frame numbers | Memory Management |
| PCB | Process control block | Processes |
| Preemption | Taking the CPU from a running thread | CPU Scheduling |
| Priority inversion | High-priority task blocked by a low-priority lock holder | Deadlock |
| Race condition | Outcome depends on thread timing | Synchronization |
| Round Robin | Each ready process runs for one quantum in turn | CPU Scheduling |
| Safe state | Some ordering lets all processes finish | Deadlock |
| Semaphore | Counter with atomic wait and signal | Synchronization |
| Spinlock | Lock that busy-waits | Synchronization |
| Starvation | A process never gets a resource | Deadlock |
| System call | Controlled entry from a program into the kernel | Kernel and System Calls |
| Thrashing | Constant paging; little useful work | Virtual Memory |
| Thread | Execution flow inside a process | Threads |
| TLB | Cache of address translations | Memory Management |
| Trap | Deliberate entry to the kernel by an instruction | Kernel and System Calls |
| Turnaround time | Completion − arrival | CPU Scheduling |
| Virtual memory | Each process sees a private address space, possibly larger than RAM | Virtual Memory |
| Waiting time | Turnaround − burst | CPU Scheduling |
| Working set | Pages a process used recently | Virtual Memory |
| Zombie | Finished process not yet reaped by its parent | Processes |
Further Reading
| Resource | Good for |
|---|---|
| Arpaci-Dusseau, Operating Systems: Three Easy Pieces (free online) | Clear beginner explanations of virtualisation, concurrency, persistence |
| Silberschatz, Galvin and Gagne, Operating System Concepts | The standard textbook; most interview problems come from here |
| The Wikipedia articles linked from each page | Quick refreshers |
| The Computer Architecture wiki | The hardware underneath: caches, memory ordering, multicore |