UNIT 3: Operating System (Exam-Focused Short Notes)
I. Operating System Fundamentals
Definition & Objectives
An Operating System (OS) is system software that acts as an intermediary between computer hardware and user applications. Its primary objectives are:
-
Convenience: Makes the system easy to use.
-
Efficiency: Manages system resources effectively.
-
Ability to Evolve: Allows for the addition of new functions and hardware.
-
Security & Protection: Prevents unauthorized access to system resources.
Major Services
| Service Category | Key Functions |
|---|---|
| Process Management | Scheduling, creation/termination, synchronization, deadlock handling. |
| Memory Management | Allocation/deallocation, paging, segmentation, virtual memory. |
| Storage Management | File system management, disk scheduling, free space management. |
| Protection & Security | Access control, authentication, preventing interference. |
| I/O System Management | Device drivers, buffering, spooling. |
Types of OS (with Examples)
| Type | Key Characteristic | Example |
|---|---|---|
| Batch | Jobs collected & executed without user interaction. | Early IBM systems. |
| Multiprogramming | Multiple programs in memory; one uses CPU while others wait. | Modern desktops. |
| Time-Sharing | CPU switches rapidly among users (quantum-based). | UNIX, Linux. |
| Real-Time | Must meet strict timing constraints (hard/soft). | Embedded systems, robotics. |
| Distributed | Manages a network of independent computers as one system. | Google's Borg, Kubernetes. |
OS Structures
-
Monolithic: All OS components in a single binary (high performance, hard to debug). Example: Traditional UNIX.
-
Layered: OS organized in layers, each using only lower layers (easier to debug, may be inefficient). Example: THE OS.
-
Microkernel: Minimal core (IPC, memory management); other services as user-space processes (more secure, slower). Example: QNX, macOS XNU.
-
Modular: Dynamic loading of OS modules (balance of flexibility & performance). Example: Modern Windows, Linux (loadable kernel modules).
System Calls
-
Concept: The programmed interface through which an application requests a service from the kernel.
-
Importance: Provides controlled access to hardware and protected resources; defines the OS's "API".
-
Types: Process control (
fork(),exit()), file management (open(),read()), device management (ioctl()), information maintenance (getpid()), communication (pipe(),shmget()).
Design Issues: Spooling & Buffering
-
Spooling (Simultaneous Peripheral Operations On-Line): Holds output data on disk (e.g., print queue) to allow processes to continue without waiting for slow I/O devices.
-
Buffering: Temporary storage of data while it's being transferred between devices or between a device and an application. Smooths out speed differences.
[!TIP] Exam Focus: Be ready to contrast OS types and structures. Know that system calls are the only way for user processes to request OS services.
II. Process Management
A. Process Concept
-
Process: A program in execution. It is an active entity with a Process Control Block (PCB).
-
PCB: The OS's data structure containing all information about a process:
- Process state, program counter, CPU registers, memory management info, accounting info, I/O status.
-
Process States & Transitions:
New → Ready → Running → Waiting → Terminated ↑ ↓ └─── Suspended ────┘- Suspension: Process moved to secondary storage (Ready/Suspend, Wait/Suspend).
-
Multiprocessor Considerations:
-
Maximum ready processes with
nCPUs:n(if all are identical and multiprogrammed). -
Ready queue size is independent of CPU count. Multiple CPUs can pull from the same ready queue.
-
B. CPU Scheduling
Scheduling Criteria
| Criterion | Description |
|---|---|
| CPU Utilization | % of time CPU is busy. |
| Throughput | # of processes completed per unit time. |
| Turnaround Time | Total time from submission to completion. TAT = Completion - Arrival |
| Waiting Time | Total time spent in ready queue. WT = TAT - Burst Time |
| Response Time | Time from request submission to first response (in time-sharing). |
Scheduling Algorithms
| Algorithm | Preemptive? | Key Idea | Pros | Cons |
|---|---|---|---|---|
| FCFS / FIFO | No | Processes run to completion in arrival order. | Simple, fair. | Convoy effect, high avg. WT. |
| SJF / SRTF | SRTF only | Shortest next CPU burst first. | Theoretically minimizes avg. WT. | Requires future knowledge; starvation. |
| Priority Scheduling | Both | Highest priority runs first. | Reflects importance. | Starvation of low-priority. |
| Round Robin (RR) | Yes | Cyclic execution with fixed time quantum (q). | Good for time-sharing, fair share. | High context switch overhead if q too small. |
| Multilevel Queue | Varies by queue | Multiple ready queues with different priorities/algorithms. | Good for partitioning users (e.g., system vs. interactive). | Scheduling between queues needed; starvation possible. |
| Multilevel Feedback Queue | Yes | Multiple queues with different q; processes move between queues based on behavior. |
Balances response & turnaround; favors I/O-bound. | Complex tuning required. |
Performance Calculation (Gantt Chart)
-
Draw Gantt Chart showing start/end times for each process.
-
Calculate for each process:
Completion Time,Turnaround Time (TAT),Waiting Time (WT). -
Compute Averages:
Avg WT = Σ WT / n,Avg TAT = Σ TAT / n. -
Normalized TAT:
TAT / Burst Time(useful for comparing efficiency).
[!TIP] Common Pitfall: For preemptive algorithms (SRTF, Priority Preemptive, RR), arrival times matter. A process arriving later can preempt a running one. Always sort by arrival time first.
C. Process Synchronization
Critical Section Problem
A code segment where a process accesses shared resources (variables, files, devices). Must satisfy:
-
Mutual Exclusion: Only one process in its CS at a time.
-
Progress: If no process is in CS and others wish to enter, the decision cannot be postponed indefinitely.
-
Bounded Waiting: There exists a bound on the number of times other processes can enter their CS after a process requests entry.
Semaphores
-
Integer variable used for signaling and coordination.
-
Types:
-
Binary Semaphore (Mutex): Values 0 or 1. Used for mutual exclusion.
-
Counting Semaphore: Integer ≥ 0. Counts available resources.
-
-
Operations (must be ATOMIC):
-
wait(S)/P(S):while (S <= 0) ; S--;(decrements, blocks if ≤0) -
signal(S)/V(S):S++;(increments, wakes a blocked process if any)
-
-
Counting Semaphore Calculation:
-
Final value
S_final = S_initial + (#V operations) - (#P operations). -
If
S_final < 0,|S_final|processes are blocked. -
Largest initial
Sfor at least one block:S_initial < (#P operations) - (#V operations).
-
TestAndSet() Implementation (Minimal Busy Waiting)
boolean TestAndSet(boolean *target) {
boolean r = *target;
*target = true;
return r;
}
void wait(boolean *lock) {
while (TestAndSet(lock)); // Busy wait
}
void signal(boolean *lock) {
*lock = false;
}
Resource Allocation Graph (RAG)
-
Vertices: Processes (
P1...) & Resource Types (R1...). -
Edges:
-
Assignment Edge:
Ri → Pj(resourceRiallocated to processPj). -
Request Edge:
Pj → Ri(processPjrequests resourceRi).
-
-
Deadlock ⇔ Cycle in the graph if each resource type has exactly one instance.
-
For multiple instances, cycle is necessary but not sufficient for deadlock.
[!TIP] Exam Tip: For semaphore problems, track
Safter eachP/V. APblocks if it would makeSnegative. For RAG, draw carefully and check for cycles.
III. Deadlock
A. Definition & Conditions
-
Deadlock: A set of processes are deadlocked if each is waiting for an event that can only be caused by another process in the set.
-
Four Necessary Conditions (ALL must hold simultaneously):
-
Mutual Exclusion: At least one resource is non-sharable.
-
Hold and Wait: A process holds at least one resource and waits for another.
-
No Preemption: Resources cannot be forcibly taken away.
-
Circular Wait: A circular chain of processes exists, where each process waits for a resource held by the next.
-
-
Deadlock vs. Starvation:
-
Deadlock: Permanent blocking; circular wait condition holds.
-
Starvation: Process waits indefinitely but could eventually proceed (e.g., always losing in priority scheduling). No circular wait.
-
B. Handling Strategies
| Strategy | Principle | Pros | Cons |
|---|---|---|---|
| Prevention | Ensure at least one necessary condition never holds. | No runtime overhead; no deadlock. | Low resource utilization; restrictive. |
| Avoidance | Allow conditions but ensure system never enters an unsafe state. Requires knowing max needs in advance. | More flexible than prevention. | Runtime overhead; requires prior knowledge (e.g., Banker's). |
| Detection & Recovery | Let deadlock occur, detect it, then recover. | No restrictions; good for rare deadlocks. | Recovery overhead; may lose work. |
| Ignorance | Assume deadlocks are rare; let them happen and reboot. | Zero overhead. | Unsuitable for critical systems. |
C. Case Studies & Calculations
Banker's Algorithm (Multiple Resource Types)
Goal: Determine if a state is safe (exists a safe sequence) or unsafe (possible deadlock). Data Structures:
-
Available: Vector of available instances of each resource. -
Max:n x mmatrix (max demand of each process). -
Allocation:n x mmatrix (currently allocated resources). -
Need = Max - Allocation(remaining need of each process).
Algorithm Steps:
-
Find a process
Pisuch thatNeed_i ≤ Available. -
If found, pretend to allocate
Allocation_iback toAvailable(Available = Available + Allocation_i), and markPias finished (add to safe sequence). -
Repeat until all processes finish (safe) or no such
Piexists (unsafe).
[!TIP] Exam Pattern: You will be given
Max,Allocation, andAvailablevectors. First computeNeedmatrix. Then apply the algorithm step-by-step to find a safe sequence or declare unsafe.
Resource Allocation Graph (RAG) Analysis
-
Single-instance resources: Deadlock iff there is a cycle.
-
Multiple-instance resources: Cycle is necessary but not sufficient. Must use wait-for graph (derived from RAG) or Banker's-like detection.
IV. Memory Management
A. Partitioning & Allocation
| Method | Description | Fragmentation | Allocation Strategy |
|---|---|---|---|
| Fixed Partitioning | Memory divided into fixed-size partitions. | Internal: Wasted space inside partition. | Process assigned to smallest fitting partition. |
| Dynamic Partitioning | Partitions of variable size, created on demand. | External: Small holes between partitions. | First-Fit, Best-Fit, Worst-Fit. |
| Compaction | Used with dynamic partitioning to reduce external fragmentation. | Requires dynamic relocation (hardware support). | Moves processes to gather all free memory into one block. |
Allocation Algorithm Comparison (for a given set of partitions & process sizes):
-
First-Fit: Allocate first block large enough. Fast, may cause external fragmentation at low addresses.
-
Best-Fit: Allocate smallest block large enough. Minimizes leftover space, slower, causes many small holes.
-
Worst-Fit: Allocate largest block. Aims for large leftover holes, generally worst performance.
B. Paging
-
Basic Concept: Divide physical memory into fixed-size frames and logical memory into same-size pages. No external fragmentation.
-
Translation:
Logical Address = Page # + Offset.Physical Address = Frame # + Offset. -
Page Table: Maps page numbers to frame numbers. Stored in memory.
-
Structures:
-
Hierarchical: Multi-level page tables (e.g., two-level for 32-bit).
-
Hashed: For large address spaces (sparse).
-
Inverted: One entry per physical frame, stores all (process, page) mapping. Used for shared memory.
-
-
Translation Lookaside Buffer (TLB): Fast associative cache for recent page table entries.
- Effective Access Time (EAT) with TLB:
$$EAT = (TLB\_hit\_ratio) \times (TLB\_access + Memory\_access) + (1 - TLB\_hit\_ratio) \times (TLB\_access + 2 \times Memory\_access)$$
(Assuming TLB miss requires two memory accesses: one for page table, one for data).
-
Protection & Sharing: Page table entries have protection bits (R/W/X). Sharing is achieved by mapping same physical frame into page tables of multiple processes.
-
Process Isolation: A process can only access frames its page table points to. The Memory Management Unit (MMU) translates logical to physical addresses using the page table; unauthorized accesses cause a trap.
C. Page Replacement Algorithms
-
FIFO: Replace oldest page. Simple, but suffers from Belady's Anomaly (more frames → more faults for some strings).
-
LRU: Replace least recently used page. Near-optimal, requires hardware/software history tracking.
-
Optimal (Belady's): Replace page whose next use is farthest in future. Theoretical minimum faults, but not implementable (needs future knowledge).
-
Reference String Analysis: Given a string of page references and
nframes, simulate the algorithm, count page faults. Firstnunique references always fault.
D. Demand Paging
-
Concept: Bring a page into memory only when it is referenced (on page fault).
-
Page Fault: Trap to OS when accessed page is not in memory.
-
Effective Access Time (EAT):
$$EAT = (1 - p) \times (memory\_access\_time) + p \times (page\_fault\_service\_time + memory\_access\_time)$$
Where `p` = page fault rate.
* `page_fault_service_time` includes: disk seek, rotational latency, transfer time, and OS overhead.
E. Thrashing
-
Cause: High page fault rate → processes spend most time paging, not executing → low CPU utilization.
-
Working Set Model: The set of pages a process has referenced in its recent window of time
Δ. IfΣ (working set sizes) > # of frames, thrashing occurs. -
Prevention:
-
Working Set Policy: OS tracks working sets; suspends processes if
Σ WS > available frames. -
Page Fault Frequency (PFF): Directly control
p. Ifptoo high, allocate more frames; if too low, take frames away.
-
F. Allocation Policies
| Policy | Description | Pros | Cons |
|---|---|---|---|
| Local Replacement | Process replaces its own pages only. | Isolates processes; predictable per-process. | May hold onto low-utility pages; lower global throughput. |
| Global Replacement | Process can replace any page in memory. | Better overall throughput; flexible. | Unpredictable per-process performance; can cause thrashing in one process to benefit others. |
V. Storage Management
A. Disk Scheduling
-
Disk Geometry: Tracks (concentric circles), Sectors (on a track), Cylinders (same track # across platters).
-
Access Time Components:
-
Seek Time: Moving arm to correct cylinder.
-
Rotational Latency (Delay): Waiting for disk to rotate to correct sector.
-
Transfer Time: Reading/writing the sector(s).
-
-
Algorithms (given request queue & initial head position):
| Algorithm | Principle | Total Head Movement | Fairness | | :--- | :--- | :--- | :--- | | FCFS | Serve in arrival order. | Often high. | Fair. | | SSTF | Serve closest request to current head. | Lower than FCFS. | May starve far requests. | | SCAN (Elevator) | Arm moves in one direction servicing requests until end, then reverses. | Good, predictable. | Fair. | | C-SCAN | Like SCAN but only services in one direction; jumps back to start without servicing. | More uniform wait than SCAN. | Fairer than SCAN? | | LOOK / C-LOOK | Like SCAN/C-SCAN but only goes as far as last request in direction. | Slightly better than SCAN. | Fair. |
Calculation: Sum the absolute differences (|next_cylinder - current_cylinder|) for the sequence of head movements.
[!TIP] Exam Pattern: You will be given a queue like
98, 183, 37, ...and head start at53. Draw the head movement path for each algorithm and sum the distances.
B. File Management
File Attributes
Name, Identifier, Type, Location, Size, Protection, Timestamps (creation, last modified, last accessed).
File Operations
Create, Delete, Read, Write, Seek, Append, Truncate.
File Access Methods
-
Sequential: Read next record (e.g., tape). Simple, slow for random.
-
Direct (Random):
Read(n)readsnth record directly (e.g., fixed-length records on disk). Fast random access. -
Indexed: Build an index (file) containing pointers to data blocks. Allows variable-length records and efficient access (e.g., ISAM).
File Allocation Methods
| Method | How | Advantages | Disadvantages |
|---|---|---|---|
| Contiguous | File occupies consecutive blocks. | Fast sequential & direct access; simple. | External fragmentation; file growth difficult. |
| Linked | Each block has pointer to next. | No external fragmentation; file grows easily. | Wasted space for pointers; slow direct access; poor reliability (lost pointer = lost tail). |
| Indexed | All pointers to data blocks are in a separate index block. | No external fragmentation; fast direct access. | Small files waste index block space; large files need multi-level/indexed allocation. |
Free Space Management
| Method | How | Pros | Cons |
|---|---|---|---|
| Bit Vector (Bitmap) | 1 bit per block (1=free, 0=allocated). | Simple, easy to find contiguous free space. | Large disk = large bitmap (memory overhead). |
| Linked List | Free blocks linked together. | No bitmap overhead. | Traversal slow; pointer storage uses block space. |
| Grouping | First free block stores addresses of many free blocks. | Fast allocation for many blocks. | Less effective as free space depletes. |
| Counting | Stores addresses of free blocks and counts of contiguous free blocks. | Fast allocation for contiguous runs. | Complex; needs updating on allocation/free. |
Variable Granularity (e.g., 4KB vs 512B):
-
Advantage: Small files use small blocks (less internal waste); large files use large blocks (fewer pointers/indirection).
-
Modification Needed: Free-space management must track both the size and starting location of free extents (use Counting or Grouping with size info).
Directory Structure
-
Single-Level: All files in one directory. Simple, naming conflict.
-
Two-Level: User directories under a master directory. No user naming conflict.
-
Tree-Structured: Hierarchical (directories/subdirectories). Unique path names.
-
Acyclic Graph: Shared files via links (hard/soft). Multiple paths.
-
General Graph: Cycles possible (needs garbage collection for deletion).
C. Disk Performance & Reliability
- Access Time Formula:
$$Access\_Time = Seek\_Time + Rotational\_Latency + Transfer\_Time$$
* `Rotational Latency ≈ (1/2) * Rotation_Time` (average).
-
Loading Time for Program: Sum of access times for all pages/blocks needed, plus transfer time.
-
Impact of Page Size:
-
Larger page: Fewer page faults (better locality), but more internal fragmentation (last page partially filled). Larger transfer time per fault.
-
Smaller page: Less internal waste, but more page faults (TLB misses, disk I/O overhead).
-
-
Application Example (Random Access to Indexed Files): Database Management Systems (DBMS). Indexed allocation (like B+ trees) allows efficient record retrieval by key without scanning entire file.
[!TIP] Exam Focus: Be prepared to calculate total head movement for all disk scheduling algorithms. Know the pros/cons of each file allocation method and which is best for DBMS (indexed). Understand the trade-off of page size on I/O and fragmentation.