Skip to content

Operating Systems: Complete MCQ Revision Notes ​

Legend: ⭐ = asked very often · ⚠️ = trap · All numerical examples were checked by running code.

Contents

  1. OS basics (types, kernels, dual mode, system calls, interrupts, booting)
  2. Processes (states, PCB, schedulers, fork/exec, zombie/orphan, IPC)
  3. Threads
  4. CPU scheduling (formulas + worked examples)
  5. Process synchronization
  6. Deadlocks (Banker's + resource formula)
  7. Memory management (paging, TLB, segmentation)
  8. Virtual memory (page faults, replacement, thrashing)
  9. File systems
  10. I/O and disk scheduling
  11. Protection and security
  12. Virtualization and Linux facts
  13. Rapid-fire trap list

1. OS Basics ​

  • OS = intermediary between user and hardware; resource allocator + control program. The kernel is the part that is always running.
  • Goals: convenience (user view) and efficient use of hardware (system view).
  • Functions: process, memory, storage/file and I/O management; protection and security; networking; user interface (CLI, GUI, batch).

1.1 Types of OS ⭐⭐ ​

TypeKey ideaNote
BatchSimilar jobs grouped and run without interactionLong turnaround
MultiprogrammingSeveral jobs in memory; CPU switches when one waits for I/OGoal: maximize CPU utilization
Time-sharing / multitaskingRapid switching (time slices) between interactive users/processesGoal: minimize response time; needs CPU scheduling + virtual memory
Multiprocessingβ‰₯ 2 CPUs sharing memory and busSMP (all CPUs peers) vs AMP (master–slave); more throughput, economy of scale, reliability (graceful degradation)
DistributedLoosely coupled networked machinesResource sharing, reliability
Real-timeStrict timing constraintsHard RT (deadline must be met: airbag, pacemaker) vs soft RT (best effort: streaming, VoIP). Examples: VxWorks, QNX, FreeRTOS, RTLinux
Embedded / mobile / network OSAndroid (Linux kernel), iOS (XNU)

Degree of multiprogramming = number of processes in memory.

1.2 Kernel structures ⭐ ​

StructureIdeaExamples
Simple (unstructured)Little separationMS-DOS
MonolithicAll services in kernel space, one address space; fast, less isolationTraditional UNIX, Linux (with loadable modules)
LayeredLayer i uses only layer iβˆ’1THE (Dijkstra)
MicrokernelMinimal kernel (IPC, basic scheduling, memory); other services in user space via message passing. More reliable/secure, slower (IPC overhead)Mach, QNX, MINIX 3, L4
ModularCore + loadable kernel modulesLinux, Solaris
HybridMix of the aboveWindows NT, macOS/iOS (XNU = Mach + BSD)
ExokernelSecurely multiplexes raw hardware; apps build abstractionsMIT research

1.3 Dual-mode operation ⭐⭐ ​

  • Mode bit: 0 = kernel (supervisor/privileged/system/monitor) mode, 1 = user mode (Galvin).
  • Privileged instructions run only in kernel mode; trying one in user mode traps to the OS.
  • Privileged: set the timer, clear memory, disable/turn off interrupts, modify the device-status table, direct I/O access, load base/limit registers, halt, set the mode bit to user.
  • Not privileged: read the clock, issue a trap / system call. (Switching from user to kernel mode happens through a trap, which user code may issue.)
  • The timer stops a user program from hogging the CPU (infinite loop).
  • x86 protection rings: ring 0 = kernel, ring 3 = user.

1.4 System calls ⭐⭐ ​

  • The interface between a running program and the OS, entered through a trap (software interrupt). Usually used via an API (POSIX, Windows API, Java API) and libraries (libc's printf() calls write()).
  • Parameter passing: registers; a block/table in memory whose address is in a register (Linux, Solaris); the stack.
CategoryUNIX examples
Process controlfork, exec, exit, wait, kill
File managementopen, read, write, close, lseek
Device managementioctl, read, write
Information maintenancegetpid, alarm, sleep, time
Communicationpipe, shmget, mmap, socket
Protectionchmod, umask, chown

1.5 Interrupts and I/O methods ​

  • Hardware interrupt (device signals the CPU) vs software interrupt / trap (exception such as divide-by-zero or invalid memory access, or a system call). The interrupt vector table holds ISR addresses. Maskable vs non-maskable (NMI, for unrecoverable errors).
  • I/O methods ⭐: programmed I/O (polling, busy-wait) β†’ interrupt-driven I/O β†’ DMA (device moves a whole block to/from memory directly; the CPU is interrupted once per block; cycle stealing).

1.6 Booting ⭐ ​

Power on β†’ firmware (BIOS/UEFI in ROM/EEPROM/flash) runs POST β†’ bootstrap loader finds the boot block (MBR = first 512-byte sector on legacy systems, or the EFI system partition) β†’ boot loader (GRUB, Windows Boot Manager) β†’ loads the kernel β†’ kernel initializes β†’ starts init/systemd (PID 1) β†’ services and login.

  • MBR: 4 primary partitions, 2 TB disk limit. GPT (with UEFI): up to 128 partitions in Windows, huge disks.
  • The bootstrap program lives in ROM/firmware because RAM is volatile.

1.7 Misc basics ​

  • The shell (command interpreter) is a user program, not part of the kernel.
  • UNIX: Bell Labs, 1969 (Ken Thompson, Dennis Ritchie; rewritten in C). Linux: Linus Torvalds, 1991 (the kernel).
  • Spooling (Simultaneous Peripheral Operations On-Line): disk used as a buffer for slow devices such as printers (queue of jobs). Buffering: memory area holding data in transit (single, double, circular). Caching: keeping a copy for faster access.
  • Memory hierarchy: registers β†’ cache (L1/L2/L3) β†’ main memory β†’ SSD β†’ HDD β†’ optical β†’ tape. Locality of reference: temporal (same item again soon) and spatial (nearby items). Cache write-through vs write-back; cache coherence on multiprocessors.

2. Processes ​

2.1 Process basics ⭐⭐ ​

  • Process = program in execution (active). Program = passive file on disk. One program can become many processes.
  • Memory layout (low β†’ high addresses): Text (code) | Data (initialized globals/statics) | BSS (uninitialized globals) | Heap (grows up) | … | Stack (function frames, locals, return addresses; grows down).
  • PCB (process control block; task_struct in Linux): PID, process state, program counter, CPU registers, CPU-scheduling info (priority, queue pointers), memory-management info (base/limit, page/segment tables), accounting info (CPU time used, limits), I/O status (open files, devices).

2.2 Process states ⭐⭐⭐ ​

  • New β†’ (admitted) β†’ Ready β†’ (dispatch) β†’ Running β†’ (exit) β†’ Terminated
  • Running β†’ Ready (interrupt, quantum expiry, preemption)
  • Running β†’ Waiting/Blocked (I/O request or event wait) β†’ Ready (I/O or event done)
  • ⚠️ Not possible: Waiting β†’ Running (must go via Ready), Ready β†’ Waiting, New β†’ Running.
  • One Running process per CPU at a time; many can be Ready or Waiting.
  • 7-state model adds Ready-Suspended and Blocked-Suspended (swapped out by the medium-term scheduler).

2.3 Schedulers ⭐⭐⭐ ​

SchedulerMoves processesRunsControls
Long-term (job)Job pool on disk β†’ ready queue in memoryInfrequently (seconds/minutes)Degree of multiprogramming; good mix of I/O-bound and CPU-bound jobs
Short-term (CPU)Ready queue β†’ CPUVery often (milliseconds)Must be very fast
Medium-termSwaps out/in (suspend/resume)OccasionallyReduces the degree of multiprogramming
  • Time-sharing systems (UNIX, Windows) often have no long-term scheduler.
  • Dispatcher: gives the CPU to the chosen process: context switch, switch to user mode, jump to the right location. Dispatch latency = time to stop one process and start another.
  • Context switch: save state into the old PCB, load the new PCB. Pure overhead; its cost depends on hardware (e.g., multiple register sets).
  • Queues: job queue, ready queue (linked list of PCBs), device (I/O) queues.
  • I/O-bound processes have many short CPU bursts; CPU-bound processes have few long ones.

2.4 Creation, termination, fork puzzles ⭐⭐⭐ ​

  • fork() creates a child with a copy of the parent's address space (copy-on-write in modern systems). Returns 0 in the child, the child's PID (> 0) in the parent, βˆ’1 on failure.
  • exec() family replaces the process image with a new program; it does not return on success.
  • wait()/waitpid(): parent waits for a child to finish and collects its exit status. exit() terminates.
  • n consecutive fork() calls β†’ 2^n processes in total (2^n βˆ’ 1 new children); a print after them runs 2^n times.
  • Short-circuit puzzles (checked by running them):
    • if (fork() && fork()) fork(); β†’ 4 processes
    • if (fork() || fork()) fork(); β†’ 5 processes
    • fork() && fork() || fork(); β†’ 5 processes
    • for (i = 0; i < n; i++) fork(); β†’ 2^n processes
  • ⚠️ printf buffering: printf("A"); fork(); printf("B\n"); prints "AB" twice, because the unflushed "A" is copied into the child. With printf("A\n") on a terminal (line-buffered) A prints once and B twice. If output is redirected to a file or pipe (fully buffered), even "A\n" prints twice.
  • Zombie: child has terminated but the parent hasn't called wait(), so its process-table entry (exit status) remains. Orphan: parent ended first; the child is adopted by init/systemd (PID 1), which reaps it. Some OSes do cascading termination (children killed with the parent).
  • Daemon: background service process (sshd, crond). Linux: PID 0 = idle/swapper, PID 1 = init/systemd.

2.5 Inter-process communication ⭐⭐ ​

Shared memoryMessage passing
A memory region shared by processes; fastest (no kernel involvement after setup)send()/receive() through the kernel; slower (system calls)
Processes must synchronize themselvesEasier; good for small data and distributed systems
  • Message passing choices: direct (name the process) vs indirect (mailboxes/ports); blocking (synchronous) vs non-blocking (asynchronous) send/receive (both blocking = rendezvous); buffering: zero capacity (sender waits), bounded, unbounded.
  • Ordinary (anonymous) pipes: unidirectional; need a parent–child relationship; exist only while the processes run (pipe(fd): fd[0] = read end, fd[1] = write end). Named pipes (FIFOs): live in the file system, usable by unrelated processes, bidirectional (half-duplex on UNIX).
  • Others: message queues, signals, sockets (IP + port), RPC, shared memory (shmget/shmat, mmap).
  • ⚠️ Galvin's bounded buffer with in/out indices (no counter) holds at most BUFFER_SIZE βˆ’ 1 items.

3. Threads ⭐⭐ ​

  • Thread = basic unit of CPU use ("lightweight process"). Own: thread ID, program counter, register set, stack. Shared with the other threads of the process: code, data (globals), heap, open files, signals.
  • Benefits: responsiveness, resource sharing, economy (cheaper to create/switch than processes), scalability on multicore.
  • Concurrency (several tasks make progress, possibly interleaved on one core) vs parallelism (tasks run at the same time on several cores).
  • Amdahl's law: speedup ≀ 1 / (S + (1 βˆ’ S)/N), S = serial fraction, N = cores. As N β†’ ∞, speedup β†’ 1/S. Example: S = 0.25 β†’ N = 2: 1.6Γ—, N = 4: 2.29Γ—, maximum 4Γ—.
User-level threads (ULT)Kernel-level threads (KLT)
Managed by a user library; kernel unawareManaged by the kernel
Fast to create and switch (no mode switch)Slower (system calls)
One blocking system call blocks the whole process (many-to-one)Other threads keep running
No true parallelism on multiple CPUs (many-to-one)True parallelism
  • Models: many-to-one (green threads; one blocking call blocks all), one-to-one (Linux, Windows; more concurrency, limit on thread count), many-to-many (many ULTs multiplexed onto ≀ KLTs), two-level (many-to-many plus optional 1:1 binding). LWPs and scheduler activations sit between ULTs and KLTs.
  • Libraries: POSIX Pthreads (pthread_create, pthread_join), Windows threads, Java threads (extend Thread / implement Runnable). Thread pools, fork-join, OpenMP.
  • Thread cancellation: asynchronous (immediate) vs deferred (target checks periodically; safer).
  • Hyper-threading / SMT: several hardware threads per core.
ProcessThread
Heavyweight; own address spaceLightweight; shares the address space
Costly context switchCheaper switch
Needs IPC to communicateCommunicates through shared memory directly
A crash is isolatedOne thread crashing can kill the whole process

4. CPU Scheduling ⭐⭐⭐ ​

  • CPU–I/O burst cycle. Scheduling decisions happen when a process (1) goes running β†’ waiting, (2) running β†’ ready, (3) waiting β†’ ready, (4) terminates. Only (1) and (4) β†’ non-preemptive (cooperative); also (2) and (3) β†’ preemptive.
  • Criteria: maximize CPU utilization and throughput; minimize turnaround, waiting and response time.

4.1 Formulas ⭐⭐⭐ ​

  • Turnaround time (TAT) = Completion time (CT) βˆ’ Arrival time (AT)
  • Waiting time (WT) = TAT βˆ’ Burst time (BT) (when there is no I/O)
  • Response time = time of first CPU allocation βˆ’ AT
  • Throughput = processes completed per unit time; CPU utilization = busy time / total time.
  • Little's law: n = Ξ» Γ— W (average queue length = arrival rate Γ— average wait).
  • Context-switch overhead: with quantum q and switch time s, CPU efficiency = q / (q + s).

4.2 Algorithms ⭐⭐⭐ ​

AlgorithmPreemptive?Starvation?Key facts
FCFSNoNoSimple; convoy effect (short jobs stuck behind a long one)
SJFNo (by default)YesOptimal (minimum average WT) for a given set of processes; needs burst prediction
SRTF (preemptive SJF)YesYesOptimal average WT when arrivals differ
PriorityEitherYes (indefinite blocking)Fix: aging. SJF = priority with priority = 1/(predicted burst)
Round RobinYes (quantum q)NoFor time-sharing; each process waits ≀ (n βˆ’ 1)Β·q for its next turn; q β†’ ∞ β‡’ FCFS; q too small β‡’ context-switch overhead; rule of thumb: ~80% of bursts < q
Multilevel queueYes (between queues)Yes (fixed priority)Processes permanently assigned to a queue (foreground RR, background FCFS); fixed priority or time-slicing between queues
Multilevel feedback queueYesAvoidable by aging (moving up)Processes move between queues; most general and most complex; favors short and I/O-bound jobs
HRRNNoNoResponse ratio = (W + S) / S (W = time waited, S = burst); favors short jobs but ages long ones
LJF / LRTFNo / YesYesAppear only in numericals
Linux CFSRed-black tree keyed by vruntime (kernel 2.6.23+); replaced by EEVDF in kernel 6.6
  • Burst prediction by exponential averaging: Ο„(n+1) = Ξ±Β·t(n) + (1 βˆ’ Ξ±)Β·Ο„(n), 0 ≀ Ξ± ≀ 1 (Ξ± = 0: ignore the last burst; Ξ± = 1: only the last burst counts; Ξ± = Β½ is common).
  • Larger q β†’ fewer context switches; average TAT does not necessarily improve as q grows.
  • SJF is a special case of priority scheduling; RR is preemptive FCFS.
  • Real-time: Rate-Monotonic (static: shorter period = higher priority; guaranteed if U = Ξ£ Cα΅’/Tα΅’ ≀ n(2^(1/n) βˆ’ 1): n = 1 β†’ 100%, 2 β†’ 82.8%, 3 β†’ 78%, ∞ β†’ 69.3%). EDF (dynamic: earliest deadline first; schedulable iff U ≀ 1).
  • Multiprocessor: asymmetric vs symmetric (SMP); processor affinity (soft/hard); load balancing (push/pull migration).
  • Evaluating algorithms: deterministic modeling, queueing models (Little's law), simulation, implementation.

4.3 Worked examples (all checked) ⭐⭐⭐ ​

  1. FCFS convoy: P1 = 24, P2 = 3, P3 = 3, all at t = 0. Order P1, P2, P3 β†’ avg WT = (0 + 24 + 27)/3 = 17. Order P2, P3, P1 β†’ (6 + 0 + 3)/3 = 3.
  2. SJF: P1 = 6, P2 = 8, P3 = 7, P4 = 3 (all at 0) β†’ run P4, P1, P3, P2 β†’ WT 3, 16, 9, 0 β†’ avg 7 (FCFS would give 10.25).
  3. SRTF: P1 (AT 0, BT 8), P2 (1, 4), P3 (2, 9), P4 (3, 5) β†’ Gantt P1 0–1 | P2 1–5 | P4 5–10 | P1 10–17 | P3 17–26 β†’ avg WT = (9 + 0 + 15 + 2)/4 = 6.5 (non-preemptive SJF gives 7.75).
  4. RR, q = 4: P1 = 24, P2 = 3, P3 = 3 (all at 0) β†’ P1 0–4 | P2 4–7 | P3 7–10 | P1 10–30 β†’ avg WT = (6 + 4 + 7)/3 = 5.67.
  5. Priority (non-preemptive, smaller number = higher priority): P1 (BT 10, pri 3), P2 (1, 1), P3 (2, 4), P4 (1, 5), P5 (5, 2) β†’ order P2, P5, P1, P3, P4 β†’ avg WT = 8.2.

Tips: always draw the Gantt chart. For RR, check the tie rule; the usual convention is that a newly arrived process joins the ready queue before the process whose quantum just expired. CPU idle gaps count in completion time, not as waiting time for processes that hadn't arrived yet.


5. Process Synchronization ⭐⭐⭐ ​

  • Race condition: the result depends on the order of access to shared data. Critical section (CS): code that touches shared resources. Structure: entry section β†’ CS β†’ exit section β†’ remainder section.
  • Requirements for a CS solution ⭐⭐⭐:
    1. Mutual exclusion: at most one process in the CS.
    2. Progress: if the CS is free, only processes not in their remainder section take part in choosing who enters next, and the choice can't be postponed forever.
    3. Bounded waiting: there is a limit on how many times others can enter after a process has requested entry (no starvation).
    • No assumptions about relative speeds or the number of CPUs.

5.1 Software solutions (two processes) ⭐⭐ ​

SolutionMutual exclusionProgressBounded waiting
Strict alternation (turn only)βœ”βœ˜ (a process must wait for its turn even if the other doesn't want the CS)βœ”
Flags only (flag[i] = true; while (flag[j]);)βœ”βœ˜ (both set flags β†’ deadlock)βœ”
Peterson (flag[] + turn)βœ”βœ”βœ”
Dekkerβœ”βœ”βœ” (first correct software solution)
Bakery (Lamport), n processesβœ”βœ”βœ”
c
// Peterson, process i (j = the other process)
flag[i] = true; turn = j;
while (flag[j] && turn == j);   // busy wait
/* critical section */
flag[i] = false;

⚠️ Peterson can fail on modern CPUs (instruction reordering) without memory barriers. All of these solutions busy-wait.

5.2 Hardware support ​

  • Disabling interrupts: works only on a uniprocessor; unsafe for user code; inefficient on multiprocessors.
  • Atomic test_and_set() and compare_and_swap(). ⚠️ A simple TSL/CAS lock gives mutual exclusion and progress but not bounded waiting (fixed by the waiting[] array algorithm).
  • Memory barriers (fences); atomic variables.
  • Mutex / spinlock: acquire()/release() must be atomic. A spinlock busy-waits: no context switch, so it suits short critical sections on multiprocessors and wastes CPU on a single core.

5.3 Semaphores (Dijkstra) ⭐⭐⭐ ​

  • Integer S changed only by atomic wait() = P() = down() and signal() = V() = up().
c
wait(S)   { while (S <= 0);  S--; }   // busy-waiting definition
signal(S) { S++; }
  • Blocking implementation: wait: S--; if S < 0, block on S's queue. signal: S++; if S ≀ 0, wake one process. A negative value βˆ’k means k processes are blocked.
  • Counting semaphore (any value; manages n instances) vs binary semaphore (0/1; similar to a mutex).
  • Final value = initial βˆ’ (number of P) + (number of V). Examples: S = 10, 6 P and 4 V β†’ 8. S = 7, 20 P and 15 V β†’ 2.
  • Mutex vs binary semaphore: a mutex has ownership (only the locker unlocks it); a semaphore is a signaling tool (anyone may signal).
  • Misuse: signal before wait (breaks mutual exclusion), wait twice (deadlock), leaving one out.
  • Ordering: to run S2 only after S1, use synch = 0. P1: S1; signal(synch). P2: wait(synch); S2.
  • Priority inversion ⭐: high-priority H waits for a lock held by low-priority L, while medium-priority M preempts L, so H effectively waits for M. Fixes: priority inheritance (L temporarily gets H's priority) or priority ceiling. (Mars Pathfinder, 1997.)

5.4 Monitors ⭐ ​

  • High-level abstract data type: shared data + procedures; only one process can be active inside the monitor at a time (mutual exclusion is automatic).
  • Condition variables: x.wait() suspends the caller; x.signal() resumes exactly one waiting process. ⚠️ If no process is waiting, signal() has no effect (a semaphore's signal always increments).
  • Signal-and-wait (Hoare) vs signal-and-continue (Mesa, Java). Java: synchronized, wait(), notify(), notifyAll().

5.5 Classic problems ⭐⭐⭐ ​

Bounded buffer (producer–consumer): mutex = 1, empty = n, full = 0.

c
// Producer                 // Consumer
wait(empty);                wait(full);
wait(mutex);                wait(mutex);
  /* add item */              /* remove item */
signal(mutex);              signal(mutex);
signal(full);               signal(empty);

⚠️ Swapping wait(empty) and wait(mutex) in the producer can deadlock (it holds mutex while waiting for an empty slot).

Readers–writers: rw_mutex = 1, mutex = 1, read_count = 0. The first reader locks rw_mutex; the last reader unlocks it. First variant (readers' preference) β†’ writers may starve. Second variant (writers' preference) β†’ readers may starve.

Dining philosophers (5 philosophers, 5 chopsticks): each picks up the left then the right chopstick using semaphores β†’ deadlock possible (everyone holds a left chopstick). Remedies: allow at most 4 at the table; pick up both only if both are free (inside a CS or monitor); asymmetric order (odd: left first, even: right first). The monitor solution is deadlock-free but starvation is still possible.

Also: sleeping barber, cigarette smokers.

  • Deadlock (all blocked forever) vs livelock (processes keep changing state but make no progress) vs starvation (one process waits indefinitely while others proceed).

6. Deadlocks ⭐⭐⭐ ​

  • Deadlock: every process in a set waits for an event (a resource release) that only another process in the set can cause.
  • Four necessary conditions (Coffman), all at the same time ⭐⭐⭐: (1) Mutual exclusion (2) Hold and wait (3) No preemption (4) Circular wait. (Circular wait implies hold-and-wait, so the four aren't fully independent.)
  • Resource allocation graph (RAG): request edge Pi β†’ Rj, assignment edge Rj β†’ Pi.
    • No cycle β‡’ no deadlock.
    • Cycle + one instance per resource type β‡’ deadlock.
    • Cycle + multiple instances β‡’ deadlock possible (a cycle is necessary, not sufficient) ⚠️.
  • Wait-for graph (resource nodes collapsed) for single-instance resources: cycle ⇔ deadlock.

6.1 Handling methods ​

  1. Prevention: make sure at least one condition can never hold.
    • Mutual exclusion: can't be denied for inherently non-sharable resources (printer, mutex); read-only files are sharable; spooling helps printers.
    • Hold and wait: request everything at the start, or request only when holding nothing β†’ low utilization, starvation.
    • No preemption: take resources from a waiting process (fine for CPU registers and memory, not for printers or mutexes).
    • Circular wait: number the resource types and request only in increasing order ⭐ (the most practical).
  2. Avoidance: use advance knowledge (maximum claims) to stay in safe states.
    • Safe state: some safe sequence <P1 … Pn> exists in which each Pi's remaining need ≀ available + resources held by all earlier Pj.
    • Safe β‡’ no deadlock. Unsafe β‡’ deadlock possible, not certain ⚠️. Deadlocked states βŠ‚ unsafe states.
    • Single instance per type: RAG with claim edges (dashed); grant a request only if no cycle forms.
    • Multiple instances: Banker's algorithm (Dijkstra). Data: Available[m], Max[n][m], Allocation[n][m], Need = Max βˆ’ Allocation. The safety algorithm is O(mΒ·nΒ²). Resource request: if Request ≀ Need and Request ≀ Available, pretend to allocate and run the safety check; grant only if the state is safe.
  3. Detection and recovery: let deadlocks happen, detect them (wait-for graph, or a Banker-like algorithm using a Request matrix, O(mΒ·nΒ²)), then recover: kill all deadlocked processes, or one at a time until the cycle breaks; or preempt resources (choose a victim, roll back, count rollbacks in the cost to avoid starvation).
  4. Ignore it (Ostrich algorithm): what most OSes do (UNIX, Linux, Windows).

6.2 Banker's worked example (Galvin, checked) ⭐⭐ ​

Totals A = 10, B = 5, C = 7. Available = (3, 3, 2).

AllocationMaxNeed
P00 1 07 5 37 4 3
P12 0 03 2 21 2 2
P23 0 29 0 26 0 0
P32 1 12 2 20 1 1
P40 0 24 3 34 3 1
  • Safe sequence: <P1, P3, P4, P2, P0> (others exist too).
  • P1 requests (1, 0, 2) β†’ granted (state stays safe; e.g., <P1, P3, P4, P0, P2>).
  • Then P4 requests (3, 3, 0) β†’ must wait (not available). P0 requests (0, 2, 0) β†’ available, but the new state would be unsafe β†’ denied.

6.3 Resource-count formula ⭐⭐⭐ ​

  • n processes, each needs at most k instances: deadlock is impossible iff R β‰₯ n(k βˆ’ 1) + 1. (Worst case: every process holds k βˆ’ 1; one extra unit lets someone finish.)
  • Different maximum needs kα΅’: R β‰₯ Ξ£(kα΅’ βˆ’ 1) + 1.
  • Maximum processes for R units: n ≀ (R βˆ’ 1)/(k βˆ’ 1).
  • Examples: 3 processes Γ— 2 units β†’ 4. 4 processes Γ— 3 units β†’ 9. Needs 3, 4, 5 β†’ 2 + 3 + 4 + 1 = 10. 6 tape drives, 2 per process β†’ at most 5 processes.

7. Memory Management ⭐⭐⭐ ​

7.1 Address binding and loading ​

  • Binding at compile time (absolute code; must know where it loads), load time (relocatable code), execution time (needs MMU hardware; the process can move while running; used by most OSes).
  • Logical (virtual) address = generated by the CPU. Physical address = seen by the memory unit. They are the same under compile/load-time binding and differ under execution-time binding.
  • MMU: adds the relocation (base) register to every logical address; the limit register gives protection (logical address must be < limit, else trap).
  • Dynamic loading: a routine is loaded only when called (no special OS support needed). Dynamic linking: linking postponed to run time (shared libraries, DLLs, .so files, via a stub); needs OS support. Static linking copies libraries into the binary.
  • Overlays: keep only the needed code/data in memory (old, programmer-managed).
  • Swapping: move a process to the backing store and back (roll out / roll in). Slow because of transfer time.

7.2 Contiguous allocation and fragmentation ⭐⭐⭐ ​

  • Fixed partitions β†’ internal fragmentation (unused space inside an allocated partition).
  • Variable partitions β†’ external fragmentation (enough total free memory, but not contiguous).
  • Placement: first fit (first hole big enough; fastest), best fit (smallest adequate hole; searches the whole list unless sorted; leaves tiny holes), worst fit (largest hole), next fit. Simulations: first fit and best fit beat worst fit in time and utilization; first fit is generally faster.
  • 50-percent rule: with first fit, N allocated blocks lose about 0.5N blocks to fragmentation, i.e., one-third of memory may be unusable.
  • Fixes for external fragmentation: compaction (only possible with execution-time binding; expensive), paging, segmentation.

Example (checked) ⭐: holes 100, 500, 200, 300, 600 KB (in order); processes 212, 417, 112, 426 KB (in order).

Strategy212417112426
First fit500 hole (leaves 288)600 (leaves 183)288 hole (leaves 176)must wait
Best fit300500200600 βœ” (all placed)
Worst fit600 (leaves 388)500 (leaves 83)388 hole (leaves 276)must wait

7.3 Paging ⭐⭐⭐ ​

  • Physical memory is divided into frames, logical memory into pages of the same size (a power of 2, typically 4 KB). No external fragmentation; internal fragmentation in the last page (half a page per process on average).
  • Logical address = page number p | offset d. Logical space 2^m, page size 2^n β†’ p has m βˆ’ n bits, d has n bits. Frames = physical memory / page size. Physical address = frame number | d.
  • Page table: one entry per page, per process. A PTE holds the frame number plus valid/invalid, protection (R/W/X), dirty (modified) and reference (accessed) bits. PTBR points to the page table; PTLR holds its length.
  • Page table size = number of pages Γ— PTE size. Example: 32-bit logical address, 4 KB pages, 4-byte PTEs β†’ 2^20 entries Γ— 4 B = 4 MB per process.
  • Without a TLB every memory reference needs 2 memory accesses (page table + data).
  • TLB (translation look-aside buffer): small, fast associative cache of PTEs (64–1,024 entries), hit ratio h.
    • EAT = hΒ·(t_TLB + t_mem) + (1 βˆ’ h)Β·(t_TLB + 2Β·t_mem) for a single-level table. With k-level paging a miss costs k + 1 memory accesses.
    • Example: h = 0.8, TLB = 20 ns, memory = 100 ns β†’ 0.8 Γ— 120 + 0.2 Γ— 220 = 140 ns. (Newer Galvin edition ignores TLB time: h = 0.8, memory = 10 ns β†’ 12 ns.)
    • ASIDs in TLB entries avoid flushing the TLB on every context switch. TLB reach = number of entries Γ— page size.
  • Shared pages: reentrant (pure, non-self-modifying) code can be shared (one copy of libc for many processes).
  • Page-table structures for large address spaces:
    • Hierarchical (multilevel): two-level for 32-bit (10 | 10 | 12 bits); x86-64 uses 4-level paging for 48-bit virtual addresses (9|9|9|9|12), 5-level for 57-bit.
    • Hashed page tables (> 32-bit; chained entries of virtual page, frame, next); clustered page tables.
    • Inverted page table: one entry per physical frame (process ID + page number) ⭐. One table for the whole system, less memory, slower lookup (search/hash), hard to share memory. (PowerPC, IA-64, UltraSPARC.)
  • Page-size trade-off: smaller pages β†’ less internal fragmentation, better locality, but bigger page tables and more TLB pressure. Larger pages β†’ smaller tables, fewer faults, more efficient I/O and better TLB reach, but more internal fragmentation. Optimal page size β‰ˆ √(2Β·sΒ·e) (s = average process size, e = PTE size). Huge pages: 2 MB / 1 GB.
  • Galvin example: page size 2,048 B, process of 72,766 B β†’ 35 pages + 1,086 B β†’ 36 frames, internal fragmentation = 2,048 βˆ’ 1,086 = 962 B.

7.4 Segmentation ⭐⭐ ​

  • Memory seen as variable-size logical segments (main program, functions, stack, symbol table, arrays). Logical address = <segment number s, offset d>.
  • Segment table: base + limit per segment. If d β‰₯ limit β†’ trap (addressing error); otherwise physical address = base + d.
  • No internal fragmentation; external fragmentation; natural per-segment protection and sharing.
  • Segmentation with paging: Intel IA-32 (segmentation β†’ linear address β†’ paging), Multics.
PagingSegmentation
Fixed-size pagesVariable-size segments
Invisible to the programmerMatches the programmer's view
Internal fragmentationExternal fragmentation
Page table holds frame numbersSegment table holds base + limit

7.5 Kernel memory allocation ​

  • Buddy system: blocks in powers of 2; quick splitting and coalescing of buddies; internal fragmentation (a 33 KB request gets 64 KB).
  • Slab allocation: caches of pre-built kernel objects; no fragmentation, fast (Linux SLAB/SLUB).

8. Virtual Memory ⭐⭐⭐ ​

  • Separates logical from physical memory: programs larger than RAM, more multiprogramming, less I/O to load/swap, sharing (libraries, fork with copy-on-write), memory-mapped files.
  • Demand paging: bring a page in only when it is referenced (lazy swapper = pager). Pure demand paging: start with no pages in memory. The valid–invalid bit marks pages that are in memory.
  • Page-fault handling ⭐⭐: (1) reference hits an invalid entry β†’ trap to the OS; (2) OS checks: invalid reference β†’ abort; valid but not in memory β†’ continue; (3) find a free frame (or replace one); (4) schedule the disk read; (5) update the page table (valid bit); (6) restart the faulting instruction.
  • EAT = (1 βˆ’ p)Β·ma + pΒ·(page-fault service time). Example: ma = 200 ns, service time = 8 ms β†’ EAT = 200 + 7,999,800Β·p ns. With p = 1/1,000 β†’ 8.2 Β΅s (about 40Γ— slower). For less than 10% slowdown, p < 2.5 Γ— 10⁻⁢ (fewer than 1 fault in ~400,000 accesses).
  • Copy-on-write: after fork(), parent and child share pages until one writes, and only that page is copied. vfork(): the child uses the parent's address space directly (parent suspended), with no copying.
  • Major vs minor page faults (minor = page already in memory, just not mapped).

8.1 Page replacement ⭐⭐⭐ ​

Needed when there is no free frame. The dirty (modify) bit lets the OS skip writing back unmodified victims (halves the I/O).

AlgorithmRuleNotes
FIFOReplace the oldest pageSimple; suffers Belady's anomaly
Optimal (OPT/MIN)Replace the page not used for the longest time in the futureFewest possible faults; not implementable (needs the future); used as a benchmark; no Belady
LRUReplace the least recently used pageGood approximation of OPT; needs hardware (counters or a stack); stack algorithm β†’ no Belady
LRU approximationsReference bit; additional-reference-bits (shift register); second chance / clock (FIFO + reference bit: if 1, clear it and skip); enhanced second chance using (reference, modify): best victim (0,0), then (0,1), (1,0), (1,1)Second chance becomes FIFO if all bits are set
LFU / MFUCounting-basedRarely used; poor approximations of OPT
  • Belady's anomaly ⭐⭐: more frames β†’ more page faults. Possible with FIFO. Reference string 1,2,3,4,1,2,5,1,2,3,4,5: FIFO with 3 frames = 9 faults, with 4 frames = 10. (LRU on the same string: 10 then 8, no anomaly.) Stack algorithms (OPT, LRU) never show it, because the pages kept with n frames are always a subset of those kept with n + 1.
  • Galvin's string 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1 with 3 frames: FIFO = 15, LRU = 12, OPT = 9 faults ⭐ (checked).
  • Page buffering: keep a pool of free frames.

8.2 Frame allocation ​

  • Minimum frames per process is set by the architecture (the most pages one instruction can touch); the maximum by physical memory.
  • Equal allocation (m/n each), proportional (aα΅’ = (sα΅’ / S)Β·m), priority-based.
  • Global replacement (victim from any process; better throughput, a process can't control its own fault rate) vs local (only from its own frames).

8.3 Thrashing ⭐⭐⭐ ​

  • A process spends more time paging than executing, because it doesn't have enough frames for its working set (degree of multiprogramming too high).
  • Vicious cycle: CPU utilization drops β†’ long-term scheduler admits more processes β†’ more faults β†’ utilization drops further.
  • Locality model: a process moves between localities; thrashing happens when Ξ£(locality sizes) > total frames.
  • Working-set model: WS(t, Ξ”) = pages referenced in the last Ξ” references; WSSα΅’ = its size; D = Ξ£ WSSα΅’. If D > m (frames available) β†’ thrashing β†’ suspend a process. Ξ” too small misses the locality; too large covers several localities.
  • Page-fault frequency (PFF): set upper and lower bounds on the fault rate; above the upper bound give the process frames, below the lower bound take frames away.
  • Remedies: local/priority replacement, working set, PFF, lower multiprogramming, more RAM.
  • Other: prepaging, TLB reach, program structure (row-major traversal of C arrays causes fewer faults), I/O interlock (lock pages used for I/O), memory-mapped files (mmap).

9. File Systems ⭐⭐ ​

  • File attributes: name, identifier, type, location, size, protection, timestamps, owner. Operations: create, open, read, write, reposition (seek), delete, truncate, append, rename.
  • Open-file tables: per-process (file pointer, access rights) + system-wide (disk location, size, open count). File locks: shared/exclusive; mandatory (Windows) vs advisory (UNIX).
  • FCB (file control block) = inode in UNIX: permissions, owner, size, timestamps, block pointers. ⚠️ The inode does not store the file name; the name lives in the directory entry.
  • Access methods: sequential (tape model: read next, write next, rewind), direct/relative (fixed-length records, read block n), indexed (index of keys β†’ blocks; ISAM).
  • Directory structures ⭐: single-level (naming conflicts), two-level (MFD β†’ one UFD per user), tree-structured (absolute/relative paths, current directory), acyclic graph (sharing via links; dangling pointers and deletion issues; reference counts), general graph (cycles allowed β†’ garbage collection and cycle checks needed).
Hard linkSoft (symbolic) link
Another directory entry for the same inodeA separate file (own inode) that stores a path
Same inode number; link count increasesDifferent inode
Data deleted only when the link count reaches 0Dangles if the target is removed
Can't cross file systems; usually not allowed for directoriesCan cross file systems and point to directories
  • Mounting attaches a file system at a mount point. The VFS (virtual file system) layer hides different FS types behind one interface.
  • Protection: access control lists; UNIX owner/group/others Γ— rwx. Octal r = 4, w = 2, x = 1: 755 = rwxr-xr-x, 644 = rw-r--r--, 777 = rwxrwxrwx, 700 = rwx------. umask 022 β†’ new files 644 (666 βˆ’ 022), new directories 755 (777 βˆ’ 022). Special bits: setuid (4), setgid (2), sticky (1, as on /tmp).

9.1 Allocation methods ⭐⭐⭐ ​

MethodProsCons
ContiguousSimple; fast sequential and direct access; few seeksExternal fragmentation; hard to grow files; size needed upfront (CD-ROM / ISO 9660; extents in modern FS)
LinkedNo external fragmentation; files grow easilyEfficient only for sequential access; pointer overhead; a lost pointer breaks the chain. FAT = linked allocation with the pointers kept in a table at the start of the volume (MS-DOS, FAT32)
IndexedDirect access; no external fragmentationIndex-block overhead (wasteful for tiny files); large files need linked, multilevel or combined index blocks

UNIX inode (combined scheme) ⭐⭐: typically 12 direct + 1 single-indirect + 1 double-indirect + 1 triple-indirect pointer (15 in total). Older UNIX used 10 direct (13 total), so always read the question.

  • Max file size = (D + N + NΒ² + NΒ³) Γ— B, where B = block size, N = B / pointer size, D = number of direct pointers.
  • B = 4 KB, 4-byte pointers β†’ N = 1,024 β†’ 48 KB + 4 MB + 4 GB + 4 TB β‰ˆ 4 TB.
  • B = 1 KB, 4-byte pointers, 10 direct β†’ N = 256 β†’ (10 + 256 + 65,536 + 16,777,216) KB β‰ˆ 16 GB.

Free-space management: bit vector/bitmap (Galvin: 1 = free, 0 = allocated; size = one bit per block, so a 1 TB disk with 4 KB blocks needs 2^28 bits = 32 MB), linked free list, grouping (first free block stores the addresses of n free blocks), counting (start address + run length), space maps (ZFS).

Directory implementation: linear list (simple, O(n) search) vs hash table (fast; collisions; fixed size).

Consistency and recovery: fsck/chkdsk; journaling (log metadata changes first: ext3/ext4, NTFS, XFS, JFS); log-structured FS; copy-on-write FS (ZFS, Btrfs, APFS); backups (full/incremental).

Common file systems: FAT32 (max file size 4 GB βˆ’ 1 byte; no permissions or journaling), exFAT (flash drives), NTFS (Windows; journaling, ACLs, MFT, compression, encryption), ext4 (Linux; extents, journaling; max file 16 TB with 4 KB blocks), XFS, Btrfs, ZFS, APFS, HFS+. NFS: v3 stateless, v4 stateful.


10. I/O and Disk Management ⭐⭐ ​

  • I/O hardware: ports, buses (PCIe), controllers; device drivers are the OS's hardware-specific code. Memory-mapped I/O (device registers appear in the address space) vs port-mapped / isolated I/O (special IN/OUT instructions).
  • Device types: block (disk: read/write/seek), character (keyboard, serial: get/put), network (socket interface).
  • Blocking I/O (process suspended) vs non-blocking (returns at once with whatever is available) vs asynchronous (returns at once; completion signaled later).
  • Kernel I/O subsystem: I/O scheduling, buffering (handles speed and transfer-size mismatches; double buffering), caching, spooling (printer queue), error handling, protection (I/O instructions are privileged).

10.1 Disk structure and timing ⭐⭐ ​

  • Platters β†’ surfaces β†’ tracks β†’ sectors (512 B or 4 KB). A cylinder = the same track on all surfaces. Capacity = surfaces Γ— tracks per surface Γ— sectors per track Γ— bytes per sector.
  • Access time = seek time + rotational latency + transfer time (+ controller overhead). Average rotational latency = Β½ rotation = 30/RPM seconds (7,200 RPM β†’ 4.17 ms; 15,000 RPM β†’ 2 ms). Transfer rate = bytes per track Γ— rotations per second.
  • Low-level (physical) formatting β†’ partitioning β†’ logical formatting (creating the file system). Boot block; bad blocks (sector sparing/forwarding, sector slipping).
  • SSDs: no seek or rotation, so FCFS/NOOP-style scheduling; wear leveling, TRIM, write amplification. Current Linux I/O schedulers: mq-deadline, BFQ, Kyber, none.

10.2 Disk scheduling ⭐⭐⭐ ​

AlgorithmBehaviorNotes
FCFSServe in arrival orderFair, no starvation, lots of head movement
SSTFNearest request nextLike SJF; can starve far requests; not optimal
SCAN (elevator)Sweep to the end of the disk, then reverseMiddle cylinders get better service
C-SCANSweep to the end, jump back to cylinder 0 without serving, sweep againMore uniform wait times
LOOKLike SCAN but reverse at the last request
C-LOOKLike C-SCAN but go only to the last request, then jump to the lowest pending request

Worked example (Galvin, checked) ⭐⭐: cylinders 0–199, head at 53, queue 98, 183, 37, 122, 14, 124, 65, 67.

AlgorithmTotal head movement
FCFS640
SSTF (53β†’65β†’67β†’37β†’14β†’98β†’122β†’124β†’183)236
SCAN toward 0 (53β†’37β†’14β†’0β†’65→…→183)236
LOOK toward 0 (53β†’37β†’14β†’65→…→183)208
SCAN toward 199 (53→…→183β†’199β†’37β†’14)331
LOOK toward 199 (53→…→183β†’37β†’14)299
C-SCAN toward 199 (…183β†’199, jump to 0, β†’14β†’37)382 counting the return jump, 183 without
C-LOOK toward 199 (…183, jump to 14, β†’37)322 counting the jump, 153 without

⚠️ Read the direction of head movement, and whether the return jump counts in C-SCAN/C-LOOK.

RAID: see the DBMS notes (0 striping, 1 mirroring, 5 distributed parity, 6 double parity, 10 mirror + stripe).


11. Protection and Security (OS) ​

  • Protection = internal mechanism controlling how processes/users access resources. Security = defense against internal and external attacks.
  • Principle of least privilege; need-to-know; domain of protection = set of <object, rights> pairs.
  • Access matrix (rows = domains, columns = objects). Implementations: global table; access control lists (per object = a column; file ACLs); capability lists (per domain = a row; like tickets); lock–key.
  • Threats: Trojan horse, trap door/backdoor, logic bomb, stack/buffer overflow, virus, worm (Morris worm, 1988), port scanning, denial of service. Defenses: authentication, ASLR, DEP/NX bit, stack canaries, sandboxing.

12. Virtualization and Linux Facts ​

  • Type 1 hypervisor (bare metal): VMware ESXi, Microsoft Hyper-V, Xen, KVM. Type 2 (hosted on an OS): VirtualBox, VMware Workstation, Parallels. Paravirtualization: the guest OS is modified (Xen).
  • Containers (Docker) = OS-level virtualization: they share the host kernel (namespaces + cgroups), so they are lighter than VMs.
  • Linux signals: SIGHUP (1), SIGINT (2, Ctrl+C), SIGKILL (9, can't be caught or ignored), SIGSEGV (11), SIGALRM (14), SIGTERM (15, default for kill), SIGSTOP (can't be caught or ignored), SIGTSTP (Ctrl+Z), SIGCHLD (sent to the parent when a child ends).
  • nice values: βˆ’20 (highest priority) to 19 (lowest), default 0; only root can lower the nice value.
  • Commands: ps, top/htop, kill, nice/renice, chmod/chown, ls -l, df (disk free), du (disk usage), free (memory), vmstat, lsof, strace (trace system calls).

13. Rapid-fire trap list ⭐⭐⭐ ​

  1. Multiprogramming β†’ CPU utilization; time-sharing β†’ response time.
  2. Mode bit 0 = kernel, 1 = user.
  3. Reading the clock and issuing a trap are non-privileged; setting the timer, disabling interrupts and I/O are privileged.
  4. fork() returns 0 to the child and the child's PID to the parent; n forks β†’ 2^n processes.
  5. Waiting β†’ Running is impossible (goes through Ready).
  6. Long-term scheduler controls the degree of multiprogramming; medium-term swaps.
  7. Threads share code, data, heap, files; not stack, registers or PC.
  8. A blocking call in a user-level thread blocks the whole process (many-to-one).
  9. SJF gives the minimum average waiting time; SRTF is its preemptive optimum.
  10. RR: q too large β†’ FCFS; too small β†’ overhead.
  11. Starvation: SJF, SRTF, priority (fix: aging). No starvation: FCFS, RR, HRRN.
  12. Peterson: mutual exclusion + progress + bounded waiting. Strict alternation fails progress.
  13. A simple TSL lock lacks bounded waiting.
  14. Semaphore final value = initial βˆ’ P + V.
  15. A monitor signal with no waiter is lost.
  16. Deadlock needs all four Coffman conditions.
  17. A RAG cycle means deadlock only with single-instance resources.
  18. Unsafe β‰  deadlocked.
  19. R β‰₯ n(k βˆ’ 1) + 1 guarantees no deadlock.
  20. Belady's anomaly β†’ FIFO (stack algorithms are immune).
  21. OPT gives the fewest faults but can't be implemented.
  22. Paging β†’ internal fragmentation; segmentation β†’ external.
  23. Inverted page table: one entry per physical frame.
  24. A TLB miss costs extra memory access(es).
  25. Thrashing: too many processes, too few frames β†’ working set / PFF.
  26. Compaction requires execution-time binding.
  27. Best fit leaves the smallest holes, worst fit the largest; first fit is fastest.
  28. Hard link shares the inode; soft link has its own inode and can dangle.
  29. SCAN goes to the disk end; LOOK stops at the last request.
  30. SSTF can starve requests; FCFS can't.