Download Operating System Suggestions and more Exercises Operating Systems in PDF only on Docsity!
Q1. Define an Operating System. What are the primary objectives
of an OS?
Definition
An Operating System (OS) is system software that acts as an intermediary between the user/application
programs and the computer hardware. It manages all hardware resources and provides a convenient, safe,
and efficient environment for executing programs.
Formal definition: "An OS is a program that controls the execution of application programs and acts as an
interface between the user and the computer hardware." — Stallings
Primary Objectives
1. Resource Abstraction
The OS hides the complexity of hardware from the programmer. Instead of programming I/O ports directly,
applications call read()/write(). The OS provides a clean, hardware-independent interface (virtual machine).
2. Resource Management
The OS efficiently allocates and de-allocates CPU time, memory, I/O devices, and files among competing
processes. Goals include maximising utilisation, minimising overhead, and ensuring fairness.
3. Resource Protection & Security
Prevents unauthorised access using dual-mode operation (user mode vs kernel mode), memory protection
registers, and access-control lists.
4. Execution Environment
Provides program loading, linking, execution services, and error handling (traps for illegal operations, divide-
by-zero, etc.).
5. Convenience / User Interface
Offers CLI (shell), GUI, or batch interfaces so users can interact with the computer without knowing
hardware details.
Two Roles at a Glance
Resource Allocator: decides who gets CPU, memory, devices — optimising efficiency and fairness. Control Program: monitors execution, prevents errors and misuse, enforces protection.
Q2. List and briefly explain the components of a Process Control
Block (PCB).
A PCB (also called a Task Control Block) is the data structure the OS maintains for each process. It is stored in
kernel memory. When a context switch occurs, the CPU state of the outgoing process is saved in its PCB.
PCB Field Description Process ID (PID) Unique integer identifying the process in the OS. Process State Current state: New, Ready, Running, Waiting, Terminated. Program Counter (PC) Address of the next instruction to be executed on resume. CPU Registers Saved values of all CPU registers (accumulators, index regs, stack pointer, flags).
PCB Field Description CPU Scheduling Info Priority, scheduling queue pointers, CPU time used so far. Memory Management Info Page table or segment table base/limit registers for this process. Accounting Information CPU time consumed, real time elapsed, time limits, account numbers. I/O Status Information List of open file descriptors, pending I/O requests, assigned devices. Parent/Child Pointers Pointer to parent PID; list of child PIDs created via fork().
The PCB is the identity card of a process. Losing a PCB means losing the process entirely.
Q3. Why is a thread called a lightweight process? State two
advantages of threads over processes.
Why "Lightweight"?
A process is a heavyweight entity — creating it requires allocating a full address space, page tables, file-
descriptor table, and PCB. A thread (unit of execution within a process) shares the code, data, heap, and
open files of its parent process and only needs its own:
- Stack (local variables and function call frames)
- Program Counter (which instruction it is executing)
- CPU Registers (for saving/restoring its own state)
Because a thread does not replicate the address space or resource tables, creation and context-switching are
far cheaper — hence "lightweight process".
Two Advantages of Threads over Processes
1. Economy (Speed of Creation & Context Switch)
Creating a new thread costs ~10-100× less time than fork()ing a new process because no new address space
or resource duplication is needed. Thread context switches only swap a small register set and stack pointer,
not full memory maps.
Example: A web server handling 10,000 concurrent connections uses a thread pool — spawning 10,
processes would be prohibitively slow.
2. Easy Data Sharing
Threads within the same process share global variables, heap, and open files directly — no IPC mechanism
(pipes, sockets, shared memory) is needed. Inter-process communication requires expensive kernel calls;
inter-thread communication is just a read/write to a shared variable.
Property Thread Process Address Space Shared with siblings Own private address space Creation Cost Low High (full copy / fork) Communication Shared memory (direct) IPC required (pipes, sockets) Context Switch Fast Slow (full TLB flush) Fault Isolation Crash kills all threads One crash does not affect others
Q4. Describe the four necessary conditions for a deadlock.
- The page table maintains the mapping — the process sees a contiguous logical address space, but
the underlying frames are scattered.
Aspect Without Paging With Paging Physical Layout Must be contiguous Scattered frames (non-contiguous) External Fragmentation Severe Eliminated Internal Fragmentation None Small (last page may be partially used) Address Translation Direct (base+offset) Via page table (page# → frame#)
Q6. Distinguish between Internal and External Fragmentation.
Feature Internal Fragmentation External Fragmentation Definition Wasted space INSIDE an allocated memory block (allocated > required). Wasted space OUTSIDE allocated blocks — free memory exists but is not contiguous. Cause Fixed partition sizes; paging (last page partially used). Dynamic memory allocation over time (allocate & free repeatedly). Location Inside the allocated block, invisible to the process. Between allocated blocks as scattered free "holes". Effect Process cannot use the extra allocated space. A new large process cannot fit despite total free memory being sufficient. Occurs In Fixed-size partitions, paging systems. Variable-size partition, segmentation. Solution Smaller page/partition sizes. Compaction (moving all free space together); paging. Example Process needs 18KB, allocated 20KB → 2KB wasted inside. Three 10KB holes exist (total 30KB) but process needs 25KB contiguous → cannot fit.
Key One-Liner
Internal = wasted INSIDE the allocated block. External = wasted OUTSIDE between blocks.
Q7. What is the role of the Dispatcher in CPU scheduling?
The Dispatcher is the OS module that actually hands over control of the CPU to the process selected by the
short-term (CPU) scheduler. It performs the mechanical work of the context switch.
Roles of the Dispatcher
5. Context Switch: Saves the state (registers, PC, flags) of the currently running process into its PCB;
loads the state of the newly selected process from its PCB.
6. Mode Switch: Switches the CPU from kernel mode back to user mode.
7. Jump to Resume: Transfers control to the correct location in the new process (the saved PC value).
Dispatch Latency
The time the dispatcher takes to stop one process and start another is called dispatch latency. It must be
kept as short as possible since it is pure overhead (no useful user work is done during this time).
Scheduler vs Dispatcher
Short-Term Scheduler: DECIDES which process runs next (policy). Dispatcher: IMPLEMENTS the decision by doing the actual context switch (mechanism).
Q8. Explain OS as a Resource Allocator and a Control Program.
1. OS as a Resource Allocator
A computer system has many resources: CPU time, memory space, file storage, I/O devices. The OS acts as a
manager that allocates these resources to processes in a fair, efficient, and conflict-free manner.
- CPU Allocation: The scheduler decides which process runs and for how long.
- Memory Allocation: The memory manager allocates frames/segments to processes, enforcing
isolation.
- I/O Device Allocation: I/O subsystem queues requests; device drivers manage hardware access.
- File System: Allocates disk space for files; controls read/write permissions.
Goal: maximise resource utilisation, minimise waiting time, ensure fairness among processes.
2. OS as a Control Program
The OS controls the execution of user programs to prevent errors and misuse of the computer. Specifically:
- Dual-Mode Operation: User mode vs kernel mode. Privileged instructions (e.g., I/O, memory
mapping) can only execute in kernel mode. Any attempt by a user program triggers a trap.
- Timer Interrupts: A hardware timer prevents any single process from monopolising the CPU
indefinitely.
- Memory Protection: Base and limit registers (or page tables) ensure one process cannot access
another's memory.
- Error Handling: The OS catches hardware errors, illegal instructions, and system faults; reports to the
user or terminates the offending process.
Q9. Primary motivations behind IPC. Explain Shared Memory and
Message Passing.
Why IPC?
Processes are normally isolated from each other for protection. But co-operating processes need to
exchange data or synchronise their actions. Motivations:
- Information Sharing: Multiple processes may need the same data (e.g., shared clipboard).
- Computation Speedup: Break a task into subtasks running in parallel.
- Modularity: Separate functions into different processes (e.g., microservices).
- Convenience: A user may run multiple related tasks (editor + compiler + print spooler).
1. Shared Memory
A region of physical memory is mapped into the address spaces of two or more cooperating processes. Once
established (via shmget/mmap system calls), processes read/write the shared region directly — no kernel
involvement per access.
- Speed: After setup, data transfer is as fast as a memory read/write — no system calls.
Q11. Why does the CPU use logical addresses while memory
hardware uses physical addresses? Explain the role of the MMU.
Logical (Virtual) Addresses
The CPU generates logical addresses — addresses relative to the start of the process's own address space (
to max). Every process independently starts at logical address 0. This provides:
- Isolation: Process A's address 0 is completely separate from Process B's address 0.
- Relocation: A process can be loaded at any physical location; code doesn't need recompilation.
- Virtual Memory: Logical space can exceed physical RAM.
Physical Addresses
Physical addresses are actual locations in RAM. The memory controller uses physical addresses to route
signals on the memory bus. The OS assigns physical frames to processes at runtime.
Role of the MMU (Memory Management Unit)
The MMU is a hardware component (inside the CPU chip or as a separate chip) that translates every logical
address generated by the CPU into a physical address before the memory bus is accessed.
8. CPU generates logical address = page_number (p) and offset (d).
9. MMU looks up p in the page table (held in RAM; cached in TLB).
10. Page table returns frame number f.
11. MMU constructs physical address = f × page_size + d.
12. Physical address is sent to the RAM bus.
If the page table entry is invalid (page not in RAM) → MMU raises a page fault exception → OS kernel
handles it (loads page from disk).
Summary
Logical address = what the CPU program sees (portable, per-process). Physical address = actual RAM location (assigned by OS at runtime). MMU = hardware translator between the two, using page/segment tables.
Q12. Define Disk Scheduling. Why is it important in a
multiprogrammed system?
Definition
Disk scheduling is the policy used by the OS to order the pending disk I/O requests so as to minimise total
head movement (seek time). When multiple processes submit disk requests simultaneously, the OS
maintains a queue and uses a scheduling algorithm to decide the order of service.
Components of Disk Access Time
- Seek Time: Time to move the read/write head to the correct track (dominant cost).
- Rotational Latency: Time waiting for the correct sector to rotate under the head.
- Transfer Time: Time to read/write the actual data.
Why Important in Multiprogrammed Systems?
- In a multiprogrammed OS, many processes simultaneously perform file I/O, generating tens to
hundreds of disk requests queued up.
- Without scheduling, FCFS service may cause the head to thrash back and forth across the disk,
wasting enormous time on seek movement.
- Good disk scheduling (SSTF, SCAN, C-LOOK) reduces average seek distance, directly improving
throughput and response time.
- Fairness: Prevents starvation of requests for tracks far from the current head position. Algorithm Strategy Starvation? FCFS Serve in arrival order No, but poor performance SSTF Serve nearest pending request first Yes (far requests may starve) SCAN (Elevator) Move in one direction, service all; reverse at end No C-SCAN Like SCAN but only services one direction; jumps back No (uniform wait) C-LOOK Like C-SCAN but only to last pending request (not disk edge) No (most efficient)
Q13. Distinguish between Starvation and Deadlock.
Feature Starvation Deadlock Definition A process waits indefinitely because other processes continuously get the resource it needs. A set of processes are ALL permanently blocked, each waiting for a resource held by another in the set. Progress Other processes DO make progress (the system is not completely stuck). NO progress — all deadlocked processes are completely blocked. Cause Unfair scheduling (priority starvation) or biased resource allocation. All 4 conditions hold: mutual exclusion, hold-and-wait, no preemption, circular wait. Example Low-priority process never gets CPU in priority scheduling. P1 holds R1 and waits for R2; P2 holds R and waits for R1. Solution Ageing (gradually raise priority of waiting processes). Prevention, avoidance (Banker's), or detection+recovery. Severity Less severe — system still works for other processes. More severe — blocked processes never proceed.
Q14(a). Five-State Process Transition Diagram
The five states and their transitions:
State Description Key Transitions New Process is being created (PCB allocated, resources assigned). New → Ready: when admitted by long-term scheduler. Ready Process has all resources except the CPU; waiting in ready queue. Ready → Running: CPU assigned by dispatcher.
1. Mutual Exclusion
If process Pi is executing in its critical section, then NO other process Pj (j ≠ i) may be executing in its critical
section simultaneously.
2. Progress
If no process is currently in the CS AND some processes wish to enter it, then the selection of which process
enters cannot be postponed indefinitely. Only processes NOT in the remainder section participate in the
decision.
3. Bounded Waiting
There must exist a bound (finite limit) on the number of times other processes can enter the CS after a
process has expressed its wish to enter and before that request is granted. This prevents starvation.
One-Line Memory Aid
Mutual Exclusion = only ONE inside at a time. Progress = the decision to enter cannot stall forever. Bounded Waiting = you will not wait forever (finite turns for others).
Q15(b). Semaphores and the Producer-Consumer Problem
Semaphore Fundamentals
A semaphore S is an integer variable accessed only through two atomic operations:
wait(S): while (S <= 0) ; S--; // P operation — decrement signal(S): S++; // V operation — increment
Types: Binary semaphore (0 or 1, acts as mutex). Counting semaphore (0 to N, controls resource pool).
Bounded-Buffer Producer-Consumer Solution
Three semaphores are used:
- mutex = 1 (binary — mutual exclusion on buffer access)
- empty = N (counting — number of empty buffer slots; N = buffer size)
- full = 0 (counting — number of filled buffer slots) PRODUCER: CONSUMER: while (true) { while (true) { produce_item(item); wait(full); wait(empty); //empty slot? wait(mutex); wait(mutex); //lock buffer item = remove_from_buffer(); add_to_buffer(item); signal(mutex); signal(mutex);//unlock signal(empty); //slot freed signal(full); //item added consume_item(item); } }
How it works
- Producer waits if buffer is FULL (empty = 0 → blocks on wait(empty)).
- Consumer waits if buffer is EMPTY (full = 0 → blocks on wait(full)).
- mutex ensures only one process accesses the buffer structure at a time.
- Critical rule: always wait on empty/full BEFORE wait(mutex) to avoid deadlock.
Q16. Evolution of OS: Batch → Multiprogrammed → Time-Sharing
Era System Type Key Features Problem Solved / Problem Introduced 1950s Simple Batch Systems Jobs submitted on punch cards; OS ran one job at a time (serial) Eliminated manual job setup. Problem: CPU idle while waiting for slow I/O. 1960s Multiprogrammed Batch Multiple jobs kept in memory; CPU switches to another job during I/O wait CPU utilisation greatly improved. Problem: No interactivity — long turnaround times. 1960s– 70s Time-Sharing (Multitasking) CPU rapidly switches between users (RR scheduling); each user gets the illusion of a dedicated machine Interactive response times. Multiple users simultaneously. Problem: More complex OS needed. 1970s– 80s Personal Computers Single-user interactive OS (CP/M, DOS, early Mac OS) Affordable computing. Problem: No protection/security between users. 1980s– 90s Distributed Systems Multiple CPUs/machines connected by network, share resources (NFS, RPC) Fault tolerance, scalability, resource sharing. Problem: Complex synchronisation across nodes. 1990s– now Real-Time & Mobile OS Hard/soft real-time guarantees (RTOS); mobile OS (Android, iOS) with battery/resource constraints Embedded & IoT systems; smartphones.
Q17. Compare LRU and FIFO Page Replacement with a Numerical
Example (3 frames)
Comparison
Feature FIFO LRU Replace Policy Oldest loaded page (first in = first out) Page not used for the longest time (least recently used) Belady's Anomaly Suffers from it (more frames can cause MORE faults) Immune (stack algorithm — more frames always ≤ faults) Implementation Easy — queue of pages in load order Harder — need timestamps or stack tracking last-use time Performance Poor for common access patterns Near-optimal in practice (exploits temporal locality) Category Not a stack algorithm Stack algorithm
Numerical Example — Reference String: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 (3 frames)
FIFO Trace
Ref Frame 1 Frame 2 Frame 3 Page Fault? 1 1 — — YES
(i) Optimal Page Replacement
Rule: Replace the page that will NOT be used for the longest time in the future (requires future knowledge —
theoretical best).
Ref F1 F2 F3 Fault? Action 7 7 — — YES Load 7 0 7 0 — YES Load 0 1 7 0 1 YES Load 1 2 2 0 1 YES Replace 7 (next use of 7 is at pos 18, furthest) 0 2 0 1 NO Hit 3 2 0 3 YES Replace 1 (next use of 1 is at pos 14, vs 2 at pos 12, vs 0 at pos 7) 0 2 0 3 NO Hit 4 4 0 3 YES Replace 2 (next use of 2 is at pos 12, vs 0 at pos 11, vs 3 at pos 10 — wait: 3 next at 9, 2 at 8 ← replace 4? Recheck: replace page with furthest next use: 2→pos8,0→pos11,3→pos9 — replace 0!) 2 4 2 3 YES Correcting above: After [7,0,1,2,0,3,0]: frames=[2,0,3]. Ref=4: futures: 2→pos8,0→pos11,3→pos9 → 0 furthest → replace 0 3 4 2 3 NO Hit (recheck frames: [4,2,3]) 0 0 2 3 YES Replace 4 (futures: 4→never,2→pos12,3→pos11 → 4 furthest) 3 0 2 3 NO Hit 2 0 2 3 NO Hit 1 0 1 3 YES Replace 2 (futures: 0→pos15,2→pos14,3→pos12 wait... 2 next at pos14,0 at 15,3 at 12 → 0 furthest? check: pos: 1 at idx13, next 2 at idx14, 0 at idx15, 1 at idx16... frames[0,2,3]: 0 next at 15, 2 next at 14, 3 next at... end → replace 3 or 0. 3 not used after: replace 3) 2 0 1 2 NO Hit (after prev correction: frames=[0,1,2] roughly) 0 0 1 2 NO Hit 1 0 1 2 NO Hit 7 7 1 2 YES Replace 0 (not used again after this point)
Ref F1 F2 F3 Fault? Action 0 7 0 2 YES Replace 1? (1 used at pos19→idx19... 2 not used again) → replace 2 1 7 0 1 YES Replace 2 if present
Clean Optimal Solution (simplified trace)
Doing a clean step-by-step with futures: String indices: 0:7, 1:0, 2:1, 3:2, 4:0, 5:3, 6:0, 7:4, 8:2, 9:3, 10:0, 11:3, 12:2, 13:1, 14:2, 15:0, 16:1, 17:7, 18:0, 19: Faults at: 7(0),0(1),1(2),2(3),3(5),4(7),1(13),7(17),0(18),1(19) — approximately 9 faults Optimal Page Faults ≈ 9 (ii) LRU Page Replacement (3 frames) Ref F1 F2 F3 Fault? 7 7 — — YES 0 7 0 — YES 1 7 0 1 YES 2 2 0 1 YES (replace 7, LRU) 0 2 0 1 NO 3 2 0 3 YES (replace 1, LRU) 0 2 0 3 NO 4 4 0 3 YES (replace 2, LRU) 2 4 0 2 YES (replace 3, LRU) 3 4 3 2 YES (replace 0, LRU) 0 0 3 2 YES (replace 4, LRU) 3 0 3 2 NO 2 0 3 2 NO 1 1 3 2 YES (replace 0, LRU) 2 1 3 2 NO 0 1 0 2 YES (replace 3, LRU) 1 1 0 2 NO 7 1 0 7 YES (replace 2, LRU) 0 1 0 7 NO 1 1 0 7 NO
LRU Page Faults = 12 (out of 20 references)
Summary
Optimal Page Faults ≈ 9 (theoretical minimum — cannot be implemented)
Comparison
FCFS: 498 cylinders — simple but inefficient (head zigzags across disk). SSTF: 250 cylinders — nearly halves movement but can starve distant requests.
Q20(a). Layered Structure of an OS — Advantages of Modular
Approach
In a layered OS, the system is divided into N levels (layers). Layer 0 = hardware; Layer N = user interface.
Each layer only uses functions provided by the layer directly below it.
Layer Name Responsibility 0 (lowest) Hardware CPU, memory, I/O devices 1 Processor Management CPU allocation, interrupt handling 2 Memory Management Memory allocation, paging, swapping 3 I/O Management Device drivers, buffering 4 File Management File system, directory structure 5 (highest) User Interface Shell, GUI, system call API
Advantages of Modular / Layered Approach
- Abstraction: Each layer hides its implementation from upper layers — clean interface.
- Ease of Debugging: If a fault occurs, it must be in the layer using a feature — narrow search.
- Modularity: A layer can be modified or replaced without affecting other layers (as long as the
interface remains unchanged).
- Reusability: Common services (e.g., memory management) are implemented once and used by all
upper layers.
- Security: Lower layers can enforce protection that upper layers cannot bypass.
Disadvantage
- Performance overhead: Every service call traverses multiple layers instead of going directly to
hardware.
- Difficulty in defining layer boundaries: Some functions span multiple layers.
Q20(b). Distributed OS vs Batch OS
Feature Batch OS Distributed OS Definition Jobs collected in batches and executed sequentially; no user interaction during execution. Multiple CPUs/machines connected by a network; present a single unified system image. Resource Sharing No sharing — one machine, one job at a time. Resources (CPU, files, memory) shared across machines over the network. Communication Not applicable (single machine). IPC via network: message passing, RPC (Remote Procedure Call), NFS. Interactivity None — user submits job and waits for output. Interactive possible; users can access remote resources.
Feature Batch OS Distributed OS Fault Tolerance Single point of failure — machine failure = system down. High fault tolerance — other nodes can take over. Complexity Simple OS design. Very complex: distributed synchronisation, consistency, deadlock across nodes. Examples IBM mainframe punch-card systems. Google's distributed computing, Hadoop clusters, cloud OS.
Q21(a). What is a Thread? Why is Multithreading More Efficient
Than Multiple Processes?
Definition
A thread is the smallest unit of CPU execution within a process. A process can contain one or more threads,
all sharing the same code, data, and heap, but each with its own stack, program counter, and register set.
Why Multithreading is More Efficient
Aspect Multiple Processes Multiple Threads (in one Process) Address Space Each process has its own separate space All threads share one address space Creation Cost fork() duplicates address space — expensive Thread creation: only allocate stack + register set — cheap Context Switch Must save/restore full memory maps, TLB flush Only switch stack pointer + registers — fast Communication IPC needed (pipes, sockets, shared memory + sync) Direct read/write to shared data structures Memory Overhead High — each process has its own page tables Low — one set of page tables for all threads Responsiveness Multi-process app stays responsive but slower Within a process: one thread can serve UI while another does I/O
Example: A web browser uses threads — one thread renders the page, one downloads images, one runs
JavaScript — all sharing the page's DOM in memory.
Q21(b). User-Level Threads vs Kernel-Level Threads
Feature User-Level Threads (ULT) Kernel-Level Threads (KLT) Management Managed by a user-space thread library (e.g., POSIX pthreads in user space). Managed and scheduled directly by the OS kernel. OS Awareness OS is unaware; sees only the process as a single entity. OS knows about each thread; can schedule individually. Scheduling Handled by the thread library scheduler (no kernel involvement). Handled by the kernel scheduler.
Condition to Break Strategy Side Effect Circular Wait Impose a total ordering on all resource types; processes must request in increasing order only. Most practical prevention: no circular chain can form. Restricts programming flexibility.
Deadlock Avoidance — Banker's Algorithm
Avoidance allows resource requests only if the resulting state is SAFE. A safe state is one in which a safe
sequence of all processes exists — every process can eventually finish using current available resources plus
resources released by earlier processes in the sequence.
Banker's Algorithm:
13. Compute Need = Max − Allocation for every process.
14. When a process Pᵢ requests resources R: check Request ≤ Need[i] and Request ≤ Available.
15. Pretend to grant: Available - = Request; Allocation[i] += Request; Need[i] - = Request.
16. Run Safety Algorithm on the new state. If SAFE → grant. If UNSAFE → roll back and make Pᵢ wait.
Prevention vs Avoidance
Prevention: eliminates a condition statically (at design time) — conservative, restricts normal operation. Avoidance: allows more concurrency but needs advance knowledge of max resource claims (Max matrix).
Q23. What is Demand Paging? Explain Steps in Handling a Page
Fault.
Demand Paging
Demand paging is a virtual memory management strategy where pages of a process are loaded into physical
memory ONLY when they are accessed (demanded), not in advance. Initially, none or only a few pages are
loaded. The rest remain on disk until referenced.
Advantages
- Physical memory holds only actively used pages — better utilisation.
- Supports processes whose total logical size exceeds physical RAM.
- Faster process start-up (no need to load entire program before first instruction).
Mechanism
Each page table entry has a valid–invalid bit: valid = page is in memory; invalid = page is not in memory.
When the CPU accesses an invalid page → page fault.
Steps in Handling a Page Fault
17. CPU executes an instruction that references a page marked INVALID in the page table.
18. Hardware trap: MMU raises a page fault exception; CPU switches to kernel mode and jumps to the
page-fault handler.
19. OS saves the state of the faulting process (registers, PC — it will be restarted).
20. Validity check: OS checks whether the address is a legal virtual address for this process. If illegal →
terminate process (segmentation fault). If legal but not in memory → continue.
21. Find a free frame: OS checks the free-frame list. If no free frame available → run page replacement
algorithm (LRU, FIFO, etc.) to select a victim page. If victim page was modified (dirty bit = 1) → write
it back to disk (swap out).
22. Disk I/O: OS issues a disk read to load the required page from the swap space or file system into the
selected free frame.
23. Process suspended: While disk I/O is in progress, the process is put in the waiting queue; CPU runs
another process.
24. I/O completion interrupt: Disk signals completion. OS updates the page table entry (set valid bit = 1,
record frame number).
25. Restart: The faulting process is moved back to the ready queue. When it next gets the CPU, it re-
executes the SAME instruction that caused the fault (now it will succeed).
Key Point
On a page fault, the OS does NOT restart from the beginning of the process. It restarts the SINGLE INSTRUCTION that caused the fault — so program execution is transparent.
Q24. Page Replacement: 1,2,3,4,1,2,5,1,2,3,4,5 (3 frames, initially
empty)
(i) FIFO — First In First Out
Rule: When a page must be replaced, remove the page that was loaded earliest (the oldest one in memory).
Ref Frame 1 Frame 2 Frame 3 Fault? Replaced 1 1 — — YES — 2 1 2 — YES — 3 1 2 3 YES — 4 4 2 3 YES Replace 1 (oldest) 1 4 1 3 YES Replace 2 (oldest) 2 4 1 2 YES Replace 3 (oldest) 5 5 1 2 YES Replace 4 (oldest) 1 5 1 2 NO Hit 2 5 1 2 NO Hit 3 5 3 2 YES Replace 1 (oldest) 4 5 3 4 YES Replace 2 (oldest) 5 5 3 4 NO Hit
FIFO Page Faults = 9 (out of 12 references)
(ii) LRU — Least Recently Used
Rule: Replace the page that has not been used for the longest time.
Ref Frame 1 Frame 2 Frame 3 Fault? LRU Victim 1 1 — — YES — 2 1 2 — YES — 3 1 2 3 YES — 4 4 2 3 YES Replace 1 (LRU: used at step