0% found this document useful (0 votes)
3 views50 pages

OS_Interview_Notes

The document provides comprehensive interview notes on operating systems, organized into six units covering foundational concepts, processes, scheduling, concurrency, deadlocks, memory management, and virtual memory. It includes definitions, types of operating systems, core functions, system calls, and the boot sequence, along with comparisons of 32-bit and 64-bit systems. Additionally, it features a quick-fire Q&A section for common interview questions related to operating systems.

Uploaded by

abhaychandru2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

OS_Interview_Notes

The document provides comprehensive interview notes on operating systems, organized into six units covering foundational concepts, processes, scheduling, concurrency, deadlocks, memory management, and virtual memory. It includes definitions, types of operating systems, core functions, system calls, and the boot sequence, along with comparisons of 32-bit and 64-bit systems. Additionally, it features a quick-fire Q&A section for common interview questions related to operating systems.

Uploaded by

abhaychandru2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OS Interview Notes

OPERATING SYSTEMS
Complete Interview-Ready Notes
Core Concepts · Diagrams · Comparison Tables · Quick-Fire Q&A

WHAT'S INSIDE
30 original lectures reorganized into 6 units — Foundations, Processes & Scheduling, Concurrency & Synchronization,
Deadlocks, Memory Management, and Virtual Memory — plus an added Interview Quick-Fire chapter covering the
questions most commonly asked in entry-level OS interviews.

Page 1 of 50
OS Interview Notes

TABLE OF CONTENTS
UNIT 1 Foundations of Operating Systems
UNIT 2 Processes & CPU Scheduling
UNIT 3 Concurrency & Synchronization
UNIT 4 Deadlocks
UNIT 5 Memory Management
UNIT 6 Virtual Memory
UNIT 7 Interview Quick-Fire Q&A (Added)

Page 2 of 50
OS Interview Notes

UNIT 1
Foundations of Operating Systems

LEC 1 · AN INTRODUCTION TO OPERATING SYSTEMS

Application software performs a specific task for the user. System software operates and controls the computer system
and provides a platform to run application software.

DEFINITION
An operating system is software that manages all the resources of a computer system — both hardware and
software — and provides an environment in which the user can execute programs conveniently and efficiently, by
hiding the underlying complexity of the hardware and acting as a resource manager.

Why do we need an OS?


● Without an OS: apps become bulky and complex (hardware-interaction code must live in the app's own codebase).
● Without an OS: a single app could exploit all resources — no fairness.
● Without an OS: there's no memory protection between programs.
● An OS is essentially a collection of system software.

Core Functions of an OS
● Provides access to computer hardware.
● Acts as the interface between the user and the hardware.
● Resource management (a.k.a. Arbitration) — memory, device, file, security, process.
● Hides underlying hardware complexity (a.k.a. Abstraction).
● Facilitates execution of application programs by providing isolation and protection.

The OS sits between the user's applications and the raw hardware

Page 3 of 50
OS Interview Notes

LEC 2 · TYPES OF OPERATING SYSTEMS

OS Goals
● Maximum CPU utilization
● Less process starvation
● Higher priority job execution

Single-Process OS
Only one process executes at a time from the ready queue. This is the oldest model (e.g., MS-DOS, 1981).

Batch-Processing OS
● User prepares a job (historically via punch cards).
● Job is submitted to the computer operator.
● Operator collects jobs from different users and sorts them into batches with similar needs.
Page 4 of 50
OS Interview Notes
● Batches are submitted to the processor one at a time; all jobs in a batch run together.

Jobs are collected, batched, and run sequentially

● Limitation: priorities can't be set for jobs that arrive later with higher priority.
● Limitation: may lead to starvation — a batch may take a long time to complete.
● Limitation: CPU may idle during I/O operations.

Multiprogramming OS
Increases CPU utilization by keeping multiple jobs (code + data) in memory, so the CPU always has something to execute if
the current job blocks on I/O.
● Single CPU; context switching between processes.
● Switch happens when the current process moves to the wait state.
● Reduces CPU idle time.

Multitasking OS
A logical extension of multiprogramming.
● Single CPU, but able to run more than one task simultaneously (via time-sharing).
● Uses context switching and time-slicing.
● Increases responsiveness; further reduces CPU idle time.

Multi-Processing OS
More than one CPU exists in a single computer.
● Increases reliability — if one CPU fails, others keep working.
● Better throughput.
● Lesser process starvation — work can shift to an idle CPU.

Distributed OS
● Manages many bunches of resources: ≥1 CPUs, ≥1 memory units, ≥1 GPUs, etc.
● Loosely connected, autonomous, interconnected computer nodes.
● A collection of independent, networked, communicating, and physically separate computational nodes.

Page 5 of 50
OS Interview Notes
Real-Time OS (RTOS)
● Guarantees error-free computation within tight time boundaries.
● Examples: air traffic control systems, robotics.

Page 6 of 50
OS Interview Notes

LEC 3 · MULTI-TASKING VS MULTI-THREADING

Program, Process, Thread


● Program: a compiled, executable file — a set of instructions ready to run. Stored on disk.
● Process: a program under execution. Resides in the computer's primary memory (RAM).
● Thread: a single sequence stream within a process; an independent, light-weight path of execution used to achieve
parallelism inside one process.
Example: in a text editor, spell-checking, formatting, and saving are handled concurrently by multiple threads of the same
process.

Aspect Multi-Tasking Multi-Threading

One process split into sub-tasks (threads), each


Definition Executing more than one task simultaneously.
with its own path of execution.

Concept More than 1 process being context-switched. More than 1 thread being context-switched.

CPU count 1 ≥ 1 (better with more than one)

Isolation & memory protection exist — OS No isolation — threads of a process share the
Isolation
allocates separate memory to each program. same memory & resources.

Thread Scheduling
Threads are scheduled based on priority. Even though threads run within a process's runtime, the OS still assigns them
processor time slices.

Thread vs Process Context Switching


Aspect Thread Switching Process Switching

Saves thread state, switches to another thread of Saves process state, switches to another process
What's saved
the same process. by restoring its state.

Doesn't switch memory address space (but PC,


Memory space Includes switching of memory address space.
registers, stack are switched).

Speed Fast Slow

CPU cache Preserved Flushed

Page 7 of 50
OS Interview Notes

LEC 4 · COMPONENTS OF AN OS

Kernel vs User Space


● Kernel: the part of the OS that interacts directly with hardware and performs the most crucial tasks. It's the
heart/core of the OS, and the very first part loaded on startup.
● User space: where application software runs; apps here don't have privileged access to hardware. Interacts with the
kernel via a GUI or CLI.
A shell (command interpreter) is the part of the OS that receives commands from users and executes them.

Functions of the Kernel


1. Process management — scheduling processes/threads, creating & deleting processes, suspending/resuming, and
enabling process synchronization/communication.
2. Memory management — allocating/deallocating memory, tracking which memory is used by which process.
3. File management — creating/deleting files & directories, mapping files to secondary storage, backup support.
4. I/O management — buffering, caching, spooling.

Term Meaning Example

Spooling Between two jobs of differing speed. Print spooling, mail spooling.

Within one job — temporary data copy between two


Buffering YouTube video buffering.
devices.

Caching Storing frequently used data for faster access. Memory caching, web caching.

Types of Kernels
Aspect Monolithic Micro Kernel Hybrid Kernel

Only core functions (memory,


All functions live in the kernel Combines both — some in kernel,
Structure process mgmt.) in kernel; file/IO
itself. some in user space.
mgmt. in user space.

Size Bulky Smaller Moderate

Less reliable — 1 module crash


Reliability More reliable & stable. Good reliability.
brings down the whole kernel.

High — fewer user/kernel mode Slower — overhead from Speed of monolithic + modularity
Performance
overheads. user/kernel mode switching. of micro.

Examples Linux, Unix, MS-DOS L4 Linux, Symbian OS, MINIX macOS, Windows NT/7/10

How does User Mode talk to Kernel Mode?


Via Inter-Process Communication (IPC). Two processes execute independently with separate memory spaces (memory
protection), but some need to communicate to work together. This is done via shared memory and message passing.

Page 8 of 50
OS Interview Notes

LEC 5 · SYSTEM CALLS

DEFINITION
A system call is a mechanism through which a user program requests a service from the kernel that it doesn't itself
have permission to perform (e.g., accessing I/O devices or communicating with other programs). System calls are the
only way a process can go from user mode into kernel mode.

Example — mkdir: mkdir is just a wrapper around the actual system call; it interacts with the kernel to ask the file
management module to create a new directory.
Example — process creation flow: User executes a process (user space) → gets a system call → exec system call creates
the process (kernel space) → control returns to user space. The transition from user space to kernel space is done via
software interrupts. System calls are implemented in C.

Layered view: user app down to hardware, crossing the user/kernel boundary via a software interrupt

Types of System Calls


Category Examples

Process Control end/abort, load/execute, create/terminate process, get/set process attributes, wait for time,

Page 9 of 50
OS Interview Notes

Category Examples

wait/signal event, allocate & free memory

File Management create/delete file, open/close, read/write/reposition, get/set file attributes

request/release device, read/write/reposition, get/set device attributes, attach/detach


Device Management
devices

Information Maintenance get/set time or date, get/set system data, get/set process/file/device attributes

create/delete connection, send/receive messages, transfer status info, attach/detach remote


Communication Management
devices

Windows vs Unix System Calls


Category Windows Unix

CreateProcess(), ExitProcess(),
Process Control fork(), exit(), wait()
WaitForSingleObject()

CreateFile(), ReadFile(), WriteFile(),


File Management open(), read(), write(), close()
CloseHandle()

SetConsoleMode(), ReadConsole(),
Device Management ioctl(), read(), write()
WriteConsole()

Info Management GetCurrentProcessID(), SetTimer(), Sleep() getpid(), alarm(), sleep()

CreatePipe(), CreateFileMapping(),
Communication pipe(), shmget(), mmap()
MapViewOfFile()

Page 10 of 50
OS Interview Notes

LEC 6 · WHAT HAPPENS WHEN YOU TURN ON YOUR COMPUTER?

Boot sequence, step by step

5. Bootloader loads
2. CPU loads firmware 3. POST — Power-On 4. BIOS/UEFI reads 6. Kernel boots,
1. Power ON (GRUB / Bootmgr /
(BIOS / UEFI) Self Test MBR / EFI partition then User Space
[Link])

5. PC powers on.
6. CPU initializes itself and looks for firmware (BIOS) stored in the BIOS chip — a ROM chip on the motherboard used to
access & set up the system at the most basic level. Modern PCs load UEFI (Unified Extensible Firmware Interface)
instead.
7. CPU runs the BIOS, which tests and initializes system hardware and loads configuration settings. If something is
wrong (e.g., missing RAM), an error is thrown and boot stops. This is the POST (Power-On Self-Test) process. UEFI
can do much more than BIOS — e.g., Intel's Management Engine is a tiny embedded OS enabling remote
management features.
8. BIOS/UEFI hands off responsibility for booting to the OS's bootloader. It looks at the MBR (Master Boot Record) — a
special boot sector at the start of a disk — or an EFI system partition, finds a small program, and runs it.
9. The bootloader is a small program with the large task of booting the rest of the OS — it boots the kernel, then user
space. Windows uses Windows Boot Manager ([Link]), most Linux systems use GRUB, and Macs use [Link].

Page 11 of 50
OS Interview Notes

LEC 7 · 32-BIT VS 64-BIT OS

Aspect 32-bit 64-bit

Registers 32-bit registers 64-bit registers

Addressable memory 2^32 addresses ≈ 4 GB physical memory 2^64 addresses ≈ 17,179,869,184 GB

Data per instruction cycle Processes 4 bytes of data per cycle Processes 8 bytes of data per cycle

Compatibility 32-bit CPU can only run 32-bit OS 64-bit CPU can run both 32-bit and 64-bit OS

Advantages of 64-bit over 32-bit


● Addressable memory: far larger address space (2^64 vs 2^32).
● Resource usage: adding excess RAM on a 32-bit OS doesn't help — a 64-bit OS will actually use it.
● Performance: larger registers allow bigger calculations per instruction cycle (there can be thousands to billions of
instruction cycles per second, depending on processor design).
● Compatibility: 64-bit CPUs run both 32-bit and 64-bit OSes.
● Graphics performance: 8-byte graphics calculations make graphics-intensive apps run faster.

Page 12 of 50
OS Interview Notes

LEC 8 · STORAGE DEVICES BASICS

Memory hierarchy — fastest & most expensive at top, slowest & cheapest at bottom

The Four Memory Types


● Register: smallest unit of storage, part of the CPU itself. Holds instructions, storage addresses, or data used
immediately by the CPU.
● Cache: additional memory that temporarily stores frequently used instructions/data for quicker CPU access.
● Main Memory: RAM.
● Secondary Memory: storage media on which the computer stores data & programs long-term.

Dimension Primary Memory Secondary Memory

Costly (registers most expensive, due to


Cost Cheaper
semiconductors & labor)

Access speed Higher (Registers > Cache > Main Memory) Lower

Storage size Smaller Larger

Volatility Volatile Non-volatile

Page 13 of 50
OS Interview Notes

UNIT 2
Processes & CPU Scheduling

LEC 9 · INTRODUCTION TO PROCESS

● Program: compiled code, ready to execute.


● Process: a program under execution.

How the OS Converts a Program into a Process


10. Load the program & static data into memory.
11. Allocate the runtime stack.
12. Allocate heap memory.
13. Handle any I/O tasks.
14. OS hands off control to main().

Layout of a process in memory

Attributes of a Process
● A process needs a unique identifying feature.
● Process table: all processes are tracked by the OS in a table-like data structure; each entry is a Process Control Block
(PCB).
● PCB: a data structure storing a process's info/attributes — process ID, program counter, state, priority, etc.

Structure of a Process Control Block (PCB)

Page 14 of 50
OS Interview Notes

WHY REGISTERS LIVE IN THE PCB


When a process's time slice expires, the current values of its registers are stored in the PCB and the process is
swapped out. When it's next scheduled, register values are read back from the PCB into the CPU registers — this is
the whole purpose of storing registers in the PCB.

Page 15 of 50
OS Interview Notes

LEC 10 · PROCESS STATES | PROCESS QUEUES

Process States
● New: OS is about to pick the program and convert it into a process (process being created).
● Ready: the process is in memory, waiting to be assigned to a processor.
● Running: instructions are being executed; CPU is allocated.
● Waiting: the process is waiting for I/O.
● Terminated: execution finished; PCB entry removed from the process table.

Process state transition diagram

Process Queues
Queue Contains Location Managed by

Job Scheduler (Long-Term


Job Queue Processes in New state Secondary memory
Scheduler / LTS)

CPU Scheduler (Short-Term


Ready Queue Processes in Ready state Main memory
Scheduler / STS)

Waiting Queue Processes in Wait state Main memory —

● Degree of multi-programming: the number of processes in memory at once — controlled by the LTS.
● Dispatcher: the OS module that gives control of the CPU to the process selected by the STS.

Page 16 of 50
OS Interview Notes

LEC 11 · SWAPPING | CONTEXT-SWITCHING | ORPHAN & ZOMBIE PROCESSES

Swapping
● Time-sharing systems may have a Medium-Term Scheduler (MTS) that removes processes from memory to reduce
the degree of multi-programming.
● Removed processes can be reintroduced into memory and continue where they left off — this is Swapping. Swap-out
and swap-in are both done by the MTS.
● Needed to improve process mix, or when memory requirements have overcommitted available memory.

Swapping between main memory and secondary storage

Context-Switching
● Switching the CPU to another process requires a state save of the current process and a state restore of a different
one.
● The kernel saves the old process's context in its PCB and loads the saved context of the new process.
● Pure overhead — no useful work happens while switching. Speed depends on memory speed and register count.

Orphan Process
A process whose parent has terminated while it's still running. Orphan processes are adopted by the init process — the
first process of the OS.

Zombie / Defunct Process


● A zombie process has finished execution but still has an entry in the process table.
● This happens because the parent hasn't yet read the child's exit status via wait(). Once it does, the zombie is
removed — a.k.a. reaping.
● The child remains a zombie until its parent reads its exit status and the entry is removed.

Page 17 of 50
OS Interview Notes

LEC 12 · INTRO TO PROCESS SCHEDULING | FCFS | CONVOY EFFECT

Process Scheduling
● The basis of multi-programming OS.
● By switching the CPU among processes, the OS keeps the computer more productive.
● Many processes sit in memory; when one must wait or its time quantum expires, the OS takes the CPU away and
gives it to another — repeating continuously.

Preemptive vs Non-Preemptive Scheduling


Aspect Non-Preemptive Preemptive

Process keeps CPU until it terminates or switches CPU taken away when time quantum expires, or
CPU release
to wait-state. process terminates/waits.

Higher — long burst-time processes can starve


Starvation Lower.
shorter ones.

CPU utilization Lower. Higher.

Goals of CPU Scheduling


● Maximum CPU utilization
● Minimum turnaround time (TAT)
● Minimum wait time
● Minimum response time
● Maximum throughput

Key Scheduling Metrics


Term Meaning

Throughput Number of processes completed per unit time.

Arrival Time (AT) Time when the process arrives in the ready queue.

Burst Time (BT) Time required by the process for its execution.

Turnaround Time (TAT) Completion Time − Arrival Time (CT − AT).

Wait Time (WT) Turnaround Time − Burst Time (TAT − BT).

Response Time Time between entering ready queue and getting the CPU for the first time.

Completion Time (CT) Time at which the process terminates.

FCFS (First-Come First-Served)


Whichever process arrives first in the ready queue gets the CPU first.

CONVOY EFFECT

Page 18 of 50
OS Interview Notes

If one process has a much longer burst time, it has a major (negative) effect on the average wait time of the other,
shorter processes — this is the Convoy Effect. Many short-resource-need processes get blocked behind one long-
running process, causing poor resource management.

Page 19 of 50
OS Interview Notes

LEC 13 · CPU SCHEDULING — SJF | PRIORITY | ROUND ROBIN

Shortest Job First (SJF) — Non-Preemptive


● The process with the least burst time is dispatched first.
● Requires estimating BT for each process in the ready queue in advance — a genuinely hard problem in practice.
● Run the lowest-time process fully, then pick the next-lowest BT job at that instant.
● Still suffers from the Convoy Effect if the very first ready process has a large BT.
● Selection criteria: AT + BT.

SJF — Preemptive (a.k.a. Shortest Remaining Time First)


● Less starvation, no convoy effect.
● Gives lower average wait time overall — scheduling a short job before a long one decreases the short job's wait
more than it increases the long job's wait.

Priority Scheduling
● Non-preemptive: priority assigned at process creation. SJF is really a special case of priority scheduling, with priority
inversely proportional to burst time.
● Preemptive: the currently running job is preempted if a new job with higher priority arrives.
● Both variants risk indefinite waiting (starvation) for low-priority jobs.

SOLUTION: AGEING
Gradually increase the priority of a process that has waited a long time — e.g., bump priority by 1 every 15 minutes
— to guarantee it eventually runs.

Round Robin (RR)


● The most popular scheduling algorithm.
● Like FCFS, but preemptive; designed for time-sharing systems.
● Selection criteria: AT + time quantum (TQ) — doesn't depend on BT.
● No process waits forever, so starvation is very low, and there's no convoy effect.
● Easy to implement, but a small TQ causes more context switches (more overhead).

Round Robin scheduling flowchart

Page 20 of 50
OS Interview Notes

Page 21 of 50
OS Interview Notes

LEC 14 · MULTI-LEVEL QUEUE (MLQ) | MULTI-LEVEL FEEDBACK QUEUE (MLFQ)

Multi-Level Queue Scheduling (MLQ)


● The ready queue is divided into multiple queues by priority.
● A process is permanently (inflexibly) assigned to one queue, based on some property — memory size, process
priority, or type.
● Each queue has its own scheduling algorithm — e.g., System Process (SP) → RR, Interactive Process (IP) → RR, Batch
Process (BP) → FCFS.

Multi-level queue scheduling — queues ordered by priority

● System process (created by the OS) has highest priority; Interactive/foreground processes need user I/O;
Batch/background processes run silently.
● Scheduling between queues is fixed-priority preemptive — e.g., the foreground queue has absolute priority over the
background queue.
● Problem: lower-level queues are only scheduled after the top-level queue is fully drained — causing starvation for
lower-priority processes, and the Convoy Effect reappears.

Multi-Level Feedback Queue Scheduling (MLFQ)


● Multiple sub-queues exist, but processes can move between queues.
● Processes are separated by the characteristics of their burst time — a CPU-heavy process is moved to a lower-
priority queue, leaving I/O-bound/interactive processes in the higher-priority queue.
● A process waiting too long in a lower-priority queue can be promoted — this form of ageing prevents starvation.
● Less starvation than MLQ, and flexible enough to be configured for a specific system's design requirements.

Full Scheduling Algorithm Comparison


FCFS SJF PSJF Priority P-Priority RR MLQ MLFQ

Design Simple Complex Complex Complex Complex Simple Complex Complex

Preemption No No Yes No Yes Yes Yes Yes

Convoy Effect Yes Yes No Yes Yes No Yes Yes

Overhead No No Yes No Yes Yes Yes Yes

Page 22 of 50
OS Interview Notes

Page 23 of 50
OS Interview Notes

UNIT 3
Concurrency & Synchronization

LEC 15 · INTRODUCTION TO CONCURRENCY

Concurrency is the execution of multiple instruction sequences at the same time — it happens whenever several process
threads run in parallel.

Threads Recap
● A single sequence stream within a process; an independent, light-weight path of execution.
● Used to achieve parallelism by dividing a process's independent tasks.

How Threads Get CPU Access


● Each thread has its own program counter.
● The OS schedules threads according to the thread-scheduling algorithm, then fetches instructions corresponding to
that thread's PC.
● I/O- or time-quantum-based context switching applies to threads too — a Thread Control Block (TCB), like a PCB,
stores thread state during switching.

DOES A SINGLE-CPU SYSTEM GAIN FROM MULTI-THREADING?


Never. Two threads still have to context-switch for the one CPU, so there's no real parallel gain — only better
structuring/responsiveness.

Benefits of Multi-Threading
● Responsiveness.
● Resource sharing — efficient sharing of resources.
● Economy — cheaper to create and context-switch threads than processes (allocating memory/resources for a whole
new process is costly).
● Utilizes multiprocessor architectures to a greater scale and efficiency.

Page 24 of 50
OS Interview Notes

LEC 16 · CRITICAL SECTION PROBLEM

Process synchronization techniques play a key role in maintaining the consistency of shared data.

Critical Section
The segment of code where processes/threads access shared resources (common variables, files) and perform writes on
them. Since processes/threads execute concurrently, any process can be interrupted mid-execution.

RACE CONDITION
Occurs when two or more threads access shared data and try to change it at the same time. Because the scheduler
can swap between threads at any moment, the order of access is unpredictable — so the result depends on the
scheduling algorithm; both threads are "racing" to access/change the data.

Solutions to Race Conditions


● Atomic operations — make the critical section execute in one CPU cycle.
● Mutual exclusion using locks.
● Semaphores.

A simple flag variable is NOT sufficient to solve race conditions.


Peterson's Solution can avoid race conditions, but only holds for exactly 2 processes/threads.

Mutex / Locks
Locks implement mutual exclusion, allowing only one thread/process into the critical section at a time.

Disadvantages of Locks
● Contention — while one thread holds the lock, others busy-wait; if the lock-holder dies, others wait forever.
● Deadlocks.
● Harder debugging.
● Starvation of high-priority threads.

Page 25 of 50
OS Interview Notes

LEC 17 · CONDITIONAL VARIABLES & SEMAPHORES

Conditional Variable
● A synchronization primitive that lets a thread wait until a certain condition occurs.
● Works together with a lock. A thread can only enter a wait state after acquiring the lock; entering wait releases the
lock, and it re-acquires the lock immediately once notified and running again.
● Used to avoid busy waiting. There is no contention here.

Semaphores
● A synchronization method — an integer equal to the number of available resources.
● Multiple threads can execute the critical section concurrently (up to the resource count).
● Allows multiple threads to access a finite instance of resources, whereas a mutex allows only one thread to access a
single shared resource at a time.

Type Value Range Notes

Binary semaphore 0 or 1 A.k.a. mutex lock.

Controls access to a resource with a finite number of


Counting semaphore Unrestricted domain
instances.

AVOIDING BUSY WAITING WITH SEMAPHORES


When wait() finds the semaphore value not positive, the process blocks itself instead of spinning — it's placed in a
waiting queue for that semaphore and switched to the Waiting state, and control passes to the CPU scheduler. When
another process calls signal(), a blocked process is woken via wakeup(), moved to Ready state, and placed back in the
ready queue.

Page 26 of 50
OS Interview Notes

LEC 20 · THE DINING PHILOSOPHERS PROBLEM

5 philosophers, 5 forks, 1 bowl — the classic synchronization problem

15. There are 5 philosophers, sitting at a circular table with 5 chairs and a bowl of noodles in the center; the table has 5
single forks (one between each pair of philosophers).
16. Each philosopher spends life in two states: Thinking (no interaction with others) and Eating.
17. To eat, a hungry philosopher tries to pick up the 2 forks adjacent to them (left and right), one at a time.
18. A fork can't be picked up if it's already taken.
19. Once a philosopher has both forks, they eat without releasing them.

Semaphore Solution — and Why It Still Deadlocks


● Each fork is modeled as a binary semaphore: Semaphore fork[5] = {1,1,1,1,1}.
● A philosopher calls wait() to acquire a fork, and signal() to release it.
● This ensures no two neighbors eat simultaneously — but it can still deadlock.

THE DEADLOCK SCENARIO


If all 5 philosophers become hungry at the same time and each picks up their left fork first, all fork semaphores drop
to 0. Each philosopher then waits forever for their right fork — a classic circular-wait deadlock.

Fixes to Avoid Deadlock


● Allow at most 4 philosophers to sit down simultaneously (breaks the circular wait).
● Allow a philosopher to pick up a fork only if both forks are available, and require picking them up atomically inside a
critical section.
● Odd-Even Rule: an odd-numbered philosopher picks up their left fork first then their right; an even-numbered
philosopher picks up right first then left.

Conclusion: semaphores alone are not enough to solve Dining Philosophers — additional enhancement rules are required
for a deadlock-free solution.

Page 27 of 50
OS Interview Notes

Page 28 of 50
OS Interview Notes

UNIT 4
Deadlocks

LEC 21 · DEADLOCKS — PART 1

In a multi-programming environment, several processes compete for a finite number of resources.

DEADLOCK (DL)
A process requests a resource (R); if R isn't available, the process waits. Sometimes that waiting process can never
proceed because the resource it needs is busy forever — this is a Deadlock. Two or more processes wait on
resources that will never free up, because those resources are held by processes that are themselves waiting.

● Deadlock is a bug in the process/thread synchronization method.


● In deadlock, processes never finish, and system resources stay tied up, blocking other jobs from starting.
● Example resources: memory space, CPU cycles, files, locks, sockets, I/O devices.
● A single resource type can have multiple instances — e.g., a system can have 2 CPUs.

How a Process Uses a Resource


20. Request the resource — lock it if free, else wait.
21. Use it.
22. Release the resource instance, making it available to others.

Circular wait: T1 holds R1 and wants R2; T2 holds R2 and wants R1

The 4 Necessary Conditions for Deadlock


All four must hold simultaneously:
● Mutual Exclusion — only one process can use a resource at a time; others must wait.
● Hold & Wait — a process holds at least one resource while waiting to acquire additional resources held by others.
● No Preemption — a resource can only be released voluntarily by the process holding it, after it completes.
● Circular Wait — a set {P0, P1, …, Pn} exists such that P0 waits for a resource held by P1, P1 waits for one held by P2,
and so on back to P0.

Page 29 of 50
OS Interview Notes

Methods for Handling Deadlocks


● Use a protocol to prevent or avoid deadlocks, so the system never enters a deadlocked state.
● Allow the system to enter a deadlocked state, then detect it and recover.
● Ignore the problem altogether and pretend deadlocks never occur (the "Ostrich Algorithm", a.k.a. deadlock
ignorance).

Page 30 of 50
OS Interview Notes

Deadlock Prevention — Breaking One of the 4 Conditions


Condition Prevention Strategy

Use locks only for non-sharable resources (sharable ones, like read-only files, can be accessed by many).
Mutual Exclusion
Can't fully deny this condition since some resources are intrinsically non-sharable.

Protocol A: a process must request & be allocated all its resources before execution begins. Protocol B: a
Hold & Wait process may request resources only when it holds none — it must release everything before requesting
more.

If a process holding resources requests one that can't be granted immediately, all its current resources
No Preemption are preempted; it restarts only once it can regain both old and new resources (risk: Livelock). Alternative:
check if a wanted resource is held by a waiting process, and preempt it for the requester.

Impose a strict global ordering on resource acquisition (e.g., all processes must lock R1 before R2) —
Circular Wait
whoever locks R1 first also gets R2.

LEC 22 · DEADLOCKS — PART 2

Deadlock Avoidance
The kernel is given advance information on which resources a process will use during its lifetime, so the system can decide
— for each request — whether the process should wait. The decision considers currently available resources, resources
currently allocated to each process, and future requests/releases.
● Safe state: a state where the system can allocate resources to each process (up to its max) in some order and still
avoid deadlock — i.e., a safe sequence exists.
● Unsafe state: the OS can't prevent processes from requesting resources in a way that could deadlock. Not all unsafe
states are deadlocks, but an unsafe state can lead to one.
● Key rule: a resource request is only approved if the resulting state is still safe.

BANKER'S ALGORITHM
When a process requests resources, the system checks whether granting them keeps the system in a safe state. If
yes, resources are allocated; if not, the process must wait until other processes release enough resources. This is the
classic algorithm for deadlock avoidance via safe-state checking.

Deadlock Detection
Resource Instances Detection Method

Wait-for graph — a deadlock exists if and only if there's a cycle in the graph. The
Single instance of each resource type
system maintains this graph and periodically searches for cycles.

Multiple instances per resource type Banker's Algorithm (used here for detection too).

Recovery from Deadlock


● Process termination: abort all deadlocked processes, or abort one at a time until the cycle breaks.
● Resource preemption: successively take resources from processes and give them to others until the cycle is broken.

Page 31 of 50
OS Interview Notes

Page 32 of 50
OS Interview Notes

UNIT 5
Memory Management

LEC 24 · MEMORY MANAGEMENT TECHNIQUES | CONTIGUOUS ALLOCATION

In a multi-programming environment, we keep multiple processes in main memory (ready queue) to maximize CPU
utilization and system responsiveness. This means we must share and manage main memory across many processes.

Logical vs Physical Address Space


Aspect Logical (Virtual) Address Physical Address

Loaded into the memory-address register of


Generated by CPU
physical memory

User CAN access the logical address of a process User can NEVER access the physical address
User access
directly. directly (only indirectly).

Existence Doesn't exist physically — a.k.a. virtual address. A real location in main memory.

Range 0 to max (R + 0) to (R + max), for base value R

Computed by — Memory Management Unit (MMU)

MMU
The runtime mapping from virtual to physical address is done by a hardware device called the Memory Management
Unit (MMU). The user's program generates and 'thinks' in logical addresses, but ultimately needs physical memory to
actually execute.

Memory Mapping & Protection


● The OS provides the Virtual Address Space (VAS) concept to isolate each process's memory.
● The relocation register holds the base address (smallest physical address, R); the limit register holds the range of
legal logical addresses.
● Every logical address must be less than the limit register value.
● MMU maps the logical address dynamically by adding the relocation register's value.
● On a context switch, the dispatcher reloads the relocation & limit registers for the new process.
● Any attempt by a user-mode program to access OS memory or another process's memory outside its legal range
triggers a trap — treated as a fatal error.

Address translation using the relocation register

Page 33 of 50
OS Interview Notes

Page 34 of 50
OS Interview Notes

Contiguous Memory Allocation


Each process is placed in a single contiguous block of memory. Two variants: Fixed and Dynamic partitioning.

Fixed Partitioning
Main memory is divided into partitions of equal or different sizes, decided in advance.

Fixed partitioning — internal & external fragmentation

Limitations of Fixed Partitioning


● Internal Fragmentation: if a process is smaller than its partition, the leftover space inside the partition is wasted.
● External Fragmentation: the total unused space across partitions can't be combined to load a bigger process, even
though enough total space exists — just not contiguously.
● Limit on process size: a process bigger than the largest partition simply can't be loaded.
● Low degree of multi-programming: partition sizes are fixed, so they can't flex to match process sizes — capping how
many processes fit.

Dynamic Partitioning
Partition size isn't declared upfront — it's decided at the time a process is loaded (process size = partition size).

Aspect Fixed Partitioning Dynamic Partitioning

Internal fragmentation Yes No

Limit on process size Yes (bounded by largest partition) No

Degree of multi-programming Low, fixed Better, flexible

Yes — still a problem, as processes finish


External fragmentation Yes
and leave scattered free gaps

Page 35 of 50
OS Interview Notes

LEC 25 · FREE SPACE MANAGEMENT

Defragmentation / Compaction
● Dynamic partitioning suffers from external fragmentation.
● Compaction moves all loaded partitions together, making the free space contiguous — a.k.a. defragmentation.
● This lets bigger processes be stored, since free partitions are merged.
● Downside: system efficiency drops during compaction, since all free spaces are being physically relocated.

Free holes are represented in the OS as a free list (a linked-list data structure).

Algorithms to Satisfy an Allocation Request from a List of Free Holes


Strategy Rule Pros / Cons

First Fit Allocate the first hole that's big enough. Simple, fast, low time complexity.

Like First Fit, but always resumes search


Next Fit Same advantages as First Fit.
from the last allocated hole.

Less internal fragmentation, but can create many tiny holes


Allocate the smallest hole that's big
Best Fit → major external fragmentation. Slow (iterates the whole
enough.
list).

Leaves large leftover holes that may fit future processes.


Worst Fit Allocate the largest available hole.
Slow (iterates the whole list).

Page 36 of 50
OS Interview Notes

LEC 26 · PAGING | NON-CONTIGUOUS MEMORY ALLOCATION

The main disadvantage of dynamic partitioning is external fragmentation — removable via compaction, but with
overhead. We need something more dynamic/flexible.

IDEA BEHIND PAGING


If we have two small non-contiguous 1KB free holes and need to allocate 2KB, contiguous allocation fails (external
fragmentation) — even though 2KB of total free space exists. What if we split the process itself into 1KB blocks?

Paging
● A memory-management scheme that permits a process's physical address space to be non-contiguous.
● Avoids external fragmentation and the need for compaction.
● Physical memory is divided into fixed-size Frames; logical memory is divided into equal-size Pages (page size = frame
size).
● Page size is usually determined by processor architecture — traditionally 4,096 bytes, though modern processors
often support multiple page sizes.

Page Table
● A data structure that stores which page maps to which frame, holding each page's base address in physical memory.
● Every CPU-generated logical address splits into a page number (p) and a page offset (d); p indexes into the page
table to find the corresponding physical frame.
● The page table is stored in main memory at process creation, with its base address stored in the process's PCB.
● A Page Table Base Register (PTBR) points to the current page table — changing page tables on a context switch only
requires updating this one register.

Logical pages mapped to physical frames via the page table

Why Paging Is Slow, and How TLB Speeds It Up


Paging is slow because there are too many memory references needed to resolve a physical address.

Translation Look-Aside Buffer (TLB)


● A hardware cache (high-speed memory) that speeds up paging by storing recent page-number → frame-number
mappings as key-value pairs.

Page 37 of 50
OS Interview Notes
● On a lookup, if the TLB already has the mapping (a TLB hit), the frame address returns directly — no need to consult
the full page table in main memory.
● On a TLB miss, the actual page table is consulted, and the resulting mapping is cached into the TLB for next time.

TLB hit vs TLB miss during address translation

ADDRESS SPACE IDENTIFIER (ASID)


Stored in each TLB entry, the ASID uniquely identifies which process a cached mapping belongs to — this lets the TLB
safely hold entries for multiple different processes at once. When resolving a virtual page number, the TLB checks
that the ASID of the currently running process matches the ASID tied to the cached entry; a mismatch is treated as a
TLB miss.

Page 38 of 50
OS Interview Notes

LEC 27 · SEGMENTATION | NON-CONTIGUOUS MEMORY ALLOCATION

An important aspect of memory management that becomes unavoidable with paging is the separation of the user's view
of memory from the actual physical memory.

SEGMENTATION
A memory management technique that supports the user's view of memory. A logical address space is a collection of
segments based on that user view; each segment has a segment number and offset: <segment-number, offset> = {s,
d}. A process is divided into variable-sized segments based on the user's view (e.g., main function in one segment,
library functions in another).

Paging is closer to the OS's view than the user's — it divides a process into uniform pages regardless of logical function
boundaries, and related parts of one function might land in different pages that aren't loaded together, hurting efficiency.
Segmentation instead groups the same type of function into one segment.

Segmentation hardware — logical address (s, d) mapped via segment table

Paging Segmentation

Basis OS-centric — fixed-size pages User-centric — variable-sized, logical segments

Internal
Yes No
fragmentation

External
No Yes
fragmentation

Table size Generally larger Generally smaller than page table

Compiler keeps related functions in one segment


Efficiency Related functions may be split across pages
— more efficient

Page 39 of 50
OS Interview Notes
Modern system architectures often implement both segmentation and paging together, in a hybrid approach.

Page 40 of 50
OS Interview Notes

UNIT 6
Virtual Memory

LEC 28 · VIRTUAL MEMORY | DEMAND PAGING | PAGE FAULTS

VIRTUAL MEMORY
A technique that allows execution of processes not completely resident in memory — giving the user the illusion of a
very large main memory, by treating part of secondary storage as main memory (swap-space).

Why Virtual Memory Helps


● Programs can be larger than physical memory.
● A program isn't constrained by available physical memory.
● Since each program takes less physical memory, more programs run at once — increasing CPU utilization &
throughput.
● Benefits both the system and the user.

Demand Paging
● A popular method of virtual memory management: pages of a process that are least used get stored in secondary
memory.
● A page is copied into main memory only when demanded — a page fault. Page replacement algorithms decide which
pages get swapped out to make room.
● Uses a Lazy Swapper — never swaps a page into memory unless it will actually be needed. (Technically a Pager, since
it works with individual pages rather than whole processes.)

How Demand Paging Works


23. When a process is swapped in, the pager guesses which pages will be used.
24. Instead of swapping in the whole process, only guessed-needed pages are brought in — avoiding reading pages into
memory that won't be used.
25. This reduces both swap time and the amount of physical memory needed.

VALID-INVALID BIT
In the page table, this bit distinguishes pages that are in memory from those on disk. Bit = 1 means the page is legal
and in memory. Bit = 0 means the page is either not in the process's logical address space, or is valid but currently
sits only on disk.

Page table when some pages are not in memory — frame number + valid-invalid bit per entry

Page 41 of 50
OS Interview Notes

Page 42 of 50
OS Interview Notes

Handling a Page Fault


If a process never touches an invalid-bit page, it runs fine without those pages ever entering memory. But accessing a
page marked invalid triggers a page fault — the paging hardware traps to the OS.

Steps in handling a page fault

26. Check an internal table (in the process's PCB) — was the memory reference valid or invalid?
27. If invalid, the process throws an exception. If valid, the pager begins to swap the page in.
28. Find a free frame from the free-frame list.
29. Schedule a disk operation to read the desired page into that newly allocated frame.
30. Once the disk read completes, update the page table to mark the page as now in memory.
31. Restart the instruction that was interrupted by the trap — the process can now access the page as if it had always
been resident.

Pure Demand Paging


● In the extreme case, a process can start executing with zero pages in memory — the first instruction immediately
faults, and the page is brought in on demand.
● Principle: never bring a page into memory until it is required.
● The Locality of Reference principle (programs tend to access a small set of pages repeatedly for stretches of time) is
what makes demand paging perform reasonably in practice, rather than page-faulting constantly.

Virtual Memory — Advantages & Disadvantages


Advantages Disadvantages

Increases the degree of multi-programming. System can become slower — swapping takes time.

User can run large apps with less real physical memory. Thrashing may occur (see below).

Page 43 of 50
OS Interview Notes

LEC 29 · PAGE REPLACEMENT ALGORITHMS

A page fault means a process tried to access a page not currently in a frame; the OS must bring it in from swap-space. If all
frames are busy, the OS must replace an existing page — the page replacement algorithm decides which one, aiming to
minimize page faults.

FIFO (First-In-First-Out)
● Replaces the oldest page in memory.
● Easy to implement, but performance isn't always good — the replaced page might be a rarely-used initialization
module (good), or a heavily-used variable initialized early (bad — causes another fault immediately).

BELADY'S ANOMALY
For LRU and Optimal replacement, increasing the number of frames always reduces (or holds steady) the page-fault
count. FIFO can break this rule — in some reference-string cases, adding more frames actually increases the number
of page faults. This strange, counter-intuitive behavior is unique to FIFO among the common algorithms.

Optimal Page Replacement


● If a page will never be referenced again, replace it. Otherwise, replace the page referenced farthest in the future.
● Gives the lowest possible page-fault rate of any algorithm.
● Impossible to implement in practice — requires future knowledge of the reference string (similar to the SJF
scheduling problem). Used only as a theoretical benchmark.

Least Recently Used (LRU)


Uses recent past as an approximation of the near future — replaces the page that hasn't been used for the longest time.

Implementation How it works

Associate a time field with each page-table entry; replace the page with the smallest (oldest)
Counters
time value.

Keep a stack of page numbers; whenever a page is referenced, remove it from its position
Stack and push it to the top. Most-recently-used stays on top, least-recently-used sinks to the
bottom. A doubly linked list is used since entries are removed from the middle.

Page 44 of 50
OS Interview Notes

Counting-Based Page Replacement


Keep a counter of how many times each page has been referenced.

Variant Rule

Actively used pages should have a large reference count; replace the page with the
Least Frequently Used (LFU)
smallest count.

Argues the page with the smallest count was probably just brought in and hasn't
Most Frequently Used (MFU)
been used yet — so replace the most-referenced page instead.

Neither MFU nor LFU is common in practice — LRU and its approximations dominate real systems.

Page 45 of 50
OS Interview Notes

LEC 30 · THRASHING

THRASHING
If a process doesn't have enough frames to support its pages in active use, it page-faults quickly. It must replace
some page — but since all its pages are actively needed, it replaces one it needs again almost immediately, causing
another fault, and another, and another. This high-paging-activity condition is called Thrashing.

A system is thrashing when it spends more time servicing page faults than actually executing processes.

As degree of multiprogramming increases, CPU utilization rises, peaks, then collapses into thrashing

Techniques to Handle Thrashing


1. Working Set Model
Based on the Locality Model: if we allocate enough frames to accommodate a process's current locality, it will only fault
when it moves to a new locality. If the allocated frames are fewer than the size of the current locality, the process is
bound to thrash.

2. Page-Fault Frequency
● Thrashing correlates with a high page-fault rate — so we directly control the page-fault rate instead.
● Too high a rate means the process needs more frames; too low a rate means it may have too many frames.
● We set upper and lower bounds on the desired page-fault rate: if it exceeds the upper limit, allocate another frame;
if it falls below the lower limit, remove a frame.
● Controlling the page-fault rate this way prevents thrashing.

Page 46 of 50
OS Interview Notes

UNIT 7 — ADDED CONTENT


Interview Quick-Fire Q&A

WHY THIS SECTION WAS ADDED


The 30 lectures above cover almost everything an entry-level OS interview tests. This chapter adds the handful of
rapid-fire questions interviewers love to ask that weren't explicitly spelled out as Q&A in the original notes — mostly
quick definitional or 'what's the difference' style questions used as warm-ups or filler between deeper topics.

LEC Q1–Q6 · GENERAL OS CONCEPTS

Q. What is the difference between a Process and a Program?


A. A program is passive — compiled code sitting on disk, ready to run. A process is active — a program in execution, with
its own memory (stack, heap, data, text), PCB, and current state.

Q. What is the difference between a Process and a Thread?


A. A process has its own independent memory space and is isolated from other processes; a thread is a lightweight unit of
execution within a process that shares memory and resources with other threads of the same process.

Q. What is a system call, and why can't user programs directly access hardware?
A. A system call is the only mechanism for a user-mode program to request a privileged service from the kernel (e.g., file
I/O, process creation). Direct hardware access is blocked so the OS can enforce protection, isolation, and fairness across
all running programs — otherwise one buggy or malicious program could corrupt others or the system.

Q. What is the difference between Kernel mode and User mode?


A. Kernel mode has unrestricted access to hardware and can execute any CPU instruction; user mode is restricted and
must go through system calls to request privileged operations. This separation protects the OS and other processes from a
misbehaving program.

Q. What is a Context Switch, and why is it 'pure overhead'?


A. It's the act of saving the CPU state of the currently running process/thread and restoring the state of the next one. It's
overhead because the CPU does zero useful application work during the switch itself — time spent switching is time not
spent computing.

Q. Why is Thread context switching faster than Process context switching?


A. Thread switching doesn't need to swap the memory address space (page tables, TLB flush) since threads of the same
process already share memory — only registers, program counter, and stack pointer change. Process switching must also
change the address space, which is far more expensive.

Page 47 of 50
OS Interview Notes

LEC Q7–Q14 · PROCESS SCHEDULING

Q. Why is Round Robin considered fair, and what's the tradeoff with time quantum size?
A. Every process gets a guaranteed CPU turn within one 'round', which prevents starvation. But if TQ is too small, context-
switch overhead dominates and throughput drops; if TQ is too large, RR starts behaving like FCFS and responsiveness
suffers.

Q. What's the difference between Turnaround Time and Response Time?


A. Turnaround Time is the total time from arrival to completion (CT − AT). Response Time is only the time until the process
first gets the CPU — relevant for interactive systems where users care about feeling responsive, not just total completion.

Q. Can SJF ever be truly implemented in a real OS? Why or why not?
A. Not perfectly — SJF requires knowing each process's exact burst time in advance, which is generally impossible. Real
systems approximate future burst time using exponential averaging of past CPU bursts of that process.

Q. What causes starvation, and what is the standard fix?


A. Starvation happens when a process is perpetually denied CPU access — commonly in priority scheduling, where low-
priority jobs keep losing to higher-priority arrivals. The standard fix is ageing: gradually increasing a waiting process's
priority the longer it waits.

Q. What is the difference between Long-Term, Short-Term, and Medium-Term Schedulers?


A. Long-Term Scheduler (Job Scheduler) decides which jobs enter the ready queue from the job pool, controlling the
degree of multi-programming. Short-Term Scheduler (CPU Scheduler) picks which ready process runs next — invoked very
frequently. Medium-Term Scheduler handles swapping processes out of memory temporarily to reduce multi-
programming load.

Q. Why does Round Robin have no Convoy Effect but FCFS does?
A. In FCFS, a long process at the front blocks everyone behind it for its entire burst. In RR, no process holds the CPU longer
than one time quantum at a time, so short processes behind a long one still get regular turns.

Q. Is Preemptive scheduling always better than Non-Preemptive?


A. Not always — preemption adds context-switch overhead and code complexity (need locks/synchronization for shared
kernel data structures). Non-preemptive scheduling is simpler and has zero switching overhead but risks starvation and
poor responsiveness.

Q. What is Priority Inversion?


A. A scenario where a high-priority task is indirectly blocked by a low-priority task holding a resource it needs, while a
medium-priority task runs freely in between — effectively inverting the intended priority order. Solved via priority
inheritance (temporarily boosting the low-priority holder's priority).

Page 48 of 50
OS Interview Notes

LEC Q15–Q21 · SYNCHRONIZATION & DEADLOCKS

Q. What's the core difference between a Mutex and a Semaphore?


A. A mutex is a locking mechanism allowing only one thread to access a single shared resource at a time, and is typically
owned/released by the same thread. A semaphore is a counter representing available instances of a resource, can be
signaled by any thread, and can allow multiple threads through concurrently (counting semaphore) or act like a mutex
(binary semaphore).

Q. What is a Race Condition, and how would you detect one in code review?
A. It's when the final outcome of concurrent operations depends on unpredictable thread interleaving. Red flags in
review: shared mutable state accessed by multiple threads without any lock, semaphore, or atomic operation guarding
reads and writes to it.

Q. List the 4 necessary conditions for deadlock, and name one way to break each.
A. Mutual Exclusion (make resources sharable where possible), Hold & Wait (require processes to request all resources
upfront), No Preemption (allow forcible resource preemption), Circular Wait (impose a global resource-ordering protocol).

Q. What's the difference between Deadlock and Starvation?


A. Deadlock is a hard stop — involved processes wait forever due to circular dependency and will never proceed.
Starvation is a soft, ongoing unfairness — a process could theoretically proceed, but is repeatedly passed over (e.g., by
higher-priority processes) indefinitely.

Q. What's the difference between Deadlock Prevention and Deadlock Avoidance?


A. Prevention removes the possibility of deadlock altogether by structurally denying one of the 4 necessary conditions.
Avoidance allows the conditions to exist but dynamically checks each resource request against a 'safe state' test (like
Banker's Algorithm) before granting it.

Q. What is a Livelock, and how is it different from a Deadlock?


A. In deadlock, processes are blocked and doing nothing. In livelock, processes keep actively changing state in response to
each other (e.g., repeatedly backing off and retrying) but make no real progress — busy, yet stuck.

Q. Why can't Peterson's Solution be used for more than 2 processes?


A. Its correctness relies on exactly 2 shared flag variables and a single 'turn' variable to guarantee mutual exclusion and
bounded waiting; generalizing this logic correctly to N processes needs a different algorithm (e.g., a bakery algorithm or
hardware-supported primitives).

Page 49 of 50
OS Interview Notes

LEC Q22–Q28 · MEMORY MANAGEMENT & VIRTUAL MEMORY

Q. Why is Paging preferred over pure Segmentation in modern OSes?


A. Paging eliminates external fragmentation entirely since every page/frame is a fixed, equal size — allocation is always
possible from any free frame, unlike segmentation's variable-sized chunks which fragment the address space over time.

Q. What's the difference between Internal and External Fragmentation, in one line each?
A. Internal fragmentation: wasted space inside an allocated block because the process is smaller than the block. External
fragmentation: wasted space between allocated blocks — total free memory exists but isn't contiguous.

Q. What happens on a TLB miss, step by step?


A. The CPU falls back to walking the actual page table in main memory to find the frame number; once found, that page-
number-to-frame mapping is inserted into the TLB so future references to that page are fast (a TLB hit).

Q. Why does Virtual Memory let you 'run a program bigger than RAM'?
A. Because only the currently needed pages of a process must be resident in physical memory at any moment — the rest
can sit in swap space on disk and get paged in on demand, so a process's logical address space can exceed physical RAM.

Q. What's the real difference between Paging and Segmentation?


A. Paging divides memory into fixed-size chunks and is invisible to the programmer/compiler — driven by the OS.
Segmentation divides a program into logically meaningful, variable-sized chunks (functions, data, stack) that reflect the
user's/compiler's view of the program.

Q. Why can Belady's Anomaly happen in FIFO but not in LRU or Optimal replacement?
A. LRU and Optimal are both 'stack algorithms' — the set of pages held with N frames is always a subset of the pages held
with N+1 frames, so adding frames can never increase faults. FIFO has no such subset guarantee, since replacement order
depends only on arrival time, not on usage patterns — so page-fault count can behave non-monotonically as frames
increase.

Q. What is Copy-on-Write (COW), and where is it used?


A. An optimization where, instead of immediately duplicating memory when a process is copied (e.g., via fork()), both
processes initially share the same physical pages marked read-only. A private copy is only made for a page the moment
either process tries to write to it — saving memory and time when much of the memory is never modified.

Page 50 of 50

You might also like