UNIT 2: Operating Systems – Comprehensive Short Notes
I. Introduction & Overview of Operating Systems
Evolution of Operating Systems
-
Batch Processing: Jobs grouped by similar requirements; no user interaction; high turnaround time.
-
Multiprogramming: Multiple jobs in memory; CPU switches to another when one waits (I/O); increases CPU utilization.
-
Time-Sharing: CPU time slices (quantum) among multiple interactive users; rapid context switching gives illusion of dedicated CPU.
-
Parallel/Distributed Systems: Multiple processors (parallel) or networked computers (distributed) working together; focus on resource sharing and scalability.
-
Real-Time Systems: Hard (strict deadlines) or soft (occasional misses tolerated); often used in embedded/control systems.
[!TIP] Exam often asks for impact on computing paradigms: Batch → throughput, Multiprogramming → CPU utilization, Time-Sharing → interactivity, Distributed → resource sharing & reliability.
Functions of an OS
-
Process Management: Scheduling, synchronization, deadlock handling.
-
Memory Management: Allocation, protection, virtual memory.
-
File Management: Organization, storage, retrieval, naming, sharing.
-
I/O Management: Device abstraction, buffering, caching.
-
Protection & Security: Access control, user authentication.
-
Resource Allocation: Allocates CPU, memory, I/O devices.
-
Error Detection: Hardware/software error handling.
Services Provided to Users & Applications
| Service Category | Examples |
|---|---|
| Program Execution | Load, run, terminate programs. |
| I/O Operations | Read/write files, devices via system calls. |
| File System Manipulation | Create, delete, open, close, seek, get attributes. |
| Communication | Inter-process communication (IPC), networking. |
| Protection | Access control, authentication, authorization. |
| Error Detection | Hardware/software error handling, recovery. |
Characteristics of an OS
-
Concurrency: Multiple activities in progress (processes/threads).
-
Virtualization: Presents virtual resources (CPU, memory) to users.
-
Persistence: Data/state survives process termination (files).
-
Sharing: Controlled sharing of resources among users/processes.
-
Security/Protection: Mechanisms to prevent unauthorized access.
-
Hardware Abstraction: Hides hardware complexity via drivers & APIs.
Operating System Structure
-
Layered Approach: OS in layers (hardware at bottom, UI at top); each layer uses only lower layers. Easier to debug, but rigid.
-
Microkernels: Minimal kernel (scheduling, memory, IPC); other services (file, device) run in user space as servers. More modular, secure, but performance overhead from IPC.
-
Modules: Loadable kernel modules (e.g., device drivers) added dynamically.
-
Process-Based Kernel: Traditional monolithic kernel where OS services run in kernel mode as processes.
Utility Programs
-
Disk Cleanup: Removes temporary/unnecessary files.
-
Antivirus: Scans for malicious software.
-
Backup: Copies data to secondary storage.
-
System Monitoring: Tools (e.g.,
top,Task Manager) to view resource usage.
II. Process Management
Process Concept
-
Process: A program in execution; an entity with its own address space, resources, and at least one thread.
-
Process Control Block (PCB): OS data structure storing process state.
| Field | Description | | :--- | :--- | | Process State | New, Ready, Running, Waiting, Terminated. | | Program Counter | Address of next instruction. | | CPU Registers | Accumulator, stack pointer, etc. | | Memory Management | Base/limit registers, page tables. | | I/O Info | Open files, I/O devices allocated. | | Accounting | CPU time used, limits. |
-
Process States & Transitions:
New → Ready (Admitted) Ready → Running (Scheduler) Running → Ready (Timeout, Preempt) Running → Waiting (I/O request) Waiting → Ready (I/O complete) Running → Terminated (Exit)DiagramCANVAS: Draw a state transition diagram with 5 ovals (New, Ready, Running, Waiting, Terminated) and arrows labeled as above.
Process Scheduling
-
CPU Scheduler: Selects a process from ready queue to run on CPU (long-term, short-term, medium-term).
-
Preemptive: OS can interrupt a running process (e.g., RR, Priority with preemption).
-
Non-Preemptive: Process runs until it terminates or blocks (e.g., FCFS, SJF non-preemptive).
-
Dispatcher: Module that gives CPU to the selected process; involves context switch, mode switch, user program jump.
CPU Scheduling Algorithms (High Frequency)
-
First-Come, First-Served (FCFS): Processes in arrival order.
-
Gantt Chart: Timeline of process execution.
-
Avg Waiting Time (AWT): $$\displaystyle \frac{\sum \text{Waiting Time}}{n} $$
-
Avg Turnaround Time (TAT): $$\displaystyle \frac{\sum (\text{Completion Time} - \text{Arrival Time})}{n} $$
-
Convoy Effect: Long process at front delays short ones.
-
-
Shortest Job First (SJF) / Shortest Remaining Time First (SRTF): Selects process with shortest next CPU burst.
-
Optimal for minimizing AWT (but requires future knowledge).
-
Preemptive version (SRTF): Preempt if new process with shorter burst arrives.
-
Starvation possible for long jobs.
-
-
Priority Scheduling: Process with highest priority (lowest number) runs.
-
Preemptive/Non-Preemptive.
-
Starvation (Indefinite blocking) → Aging (gradually increase priority of waiting processes).
-
-
Round Robin (RR): Each process gets a fixed time quantum (q). Cyclically moves through ready queue.
-
Context switch occurs if burst > q.
-
AWT decreases as q decreases, but context switch overhead increases.
-
q too large → FCFS; q too small → high overhead.
-
[!TIP] Gantt Chart is mandatory for scheduling calculations. Always calculate Waiting Time = Start Time - Arrival Time (for first run) or sum of waiting periods. Turnaround Time = Completion Time - Arrival Time.
Threads (High Frequency)
-
Thread: Basic unit of CPU utilization; part of a process; shares process resources (memory, files) but has its own Thread Control Block (TCB) with registers, stack, program counter, thread ID.
-
Benefits: Responsiveness, resource sharing, economy (creation/switch faster than process), scalability (parallelism on MP).
-
User-Level Threads (ULT): Managed by user-space thread library; kernel unaware. Fast creation/switch, non-blocking syscalls block all threads.
-
Kernel-Level Threads (KLT): Managed by OS kernel. Syscalls can block one thread, scheduler can schedule another. Slower than ULT.
-
Comparison:
| Aspect | User-Level Threads | Kernel-Level Threads | | :--- | :--- | :--- | | Management | User library | OS kernel | | Creation/Switch | Fast (no mode switch) | Slower (mode switch) | | Blocking Syscall | Blocks entire process | Blocks only calling thread | | Scheduling | User-controlled | OS scheduler-controlled | | Multiprocessor | One process on one CPU | Threads can run on different CPUs |
Interprocess Communication (IPC)
-
Shared Memory: Processes share a region of memory. Fastest IPC. Requires synchronization (semaphores) to avoid race conditions.
-
Message Passing: Processes exchange messages via OS-provided primitives (
send,receive). Can be direct/indirect, synchronous/asynchronous. -
Pipes: Unidirectional byte stream between related processes (parent-child). Anonymous pipes (no name, temporary).
-
Named Pipes (FIFOs): Have a name in filesystem; allow communication between unrelated processes.
Synchronization & Concurrency (High Frequency)
-
Critical Section Problem: Code segment accessing shared resource that must execute atomically.
- Requirements: Mutual exclusion, progress, bounded wait.
-
Peterson’s Solution: For two processes using shared
flag[]andturnvariables. Works for two only; not practical due to busy waiting. -
Semaphores: Integer variable
Swith two atomic operations:-
wait(S)/P(S):while (S <= 0); S--; -
signal(S)/V(S):S++; -
Counting semaphore: Integer value; multiple resources.
-
Binary semaphore (mutex): Value 0/1; for mutual exclusion.
-
-
Monitors: High-level synchronization construct; procedures, shared variables, condition variables. Only one process active in monitor at a time.
- Condition Variables:
wait(cv)(release monitor & block),signal(cv)(wake one waiting).
- Condition Variables:
-
Dining Philosophers Problem:
Nphilosophers,Nforks. Solution with monitor:enum {THINKING, HUNGRY, EATING}states;test()to check neighbors;take_forks(),put_forks(). -
Real vs Virtual Concurrency:
-
Real Concurrency: Multiple CPUs/cores; true parallel execution.
-
Virtual Concurrency: Uniprocessor; rapid context switching creates illusion.
-
Deadlock (High Frequency)
-
Definition: Set of processes blocked; each holds resource and waits for another in the set.
-
Necessary Conditions (Coffman Conditions):
-
Mutual Exclusion: Resource non-shareable.
-
Hold and Wait: Process holds resource while waiting for another.
-
No Preemption: Resources cannot be forcibly taken.
-
Circular Wait: Circular chain of processes waiting for resources.
-
-
Deadlock Handling:
-
Prevention: Ensure at least one condition never holds.
-
Attacking Hold & Wait: Request all resources at start.
-
Attacking No Preemption: Preempt resources (difficult).
-
Attacking Circular Wait: Impose total ordering on resources.
-
-
Avoidance: Dynamically check if allocation leaves system in safe state.
-
Banker’s Algorithm: For multiple resource types.
-
Need[i,j] = Max[i,j] - Allocation[i,j]
-
Safe State: Exist sequence where each process can get its
NeedfromAvailable+ resources of finished processes. -
Request Handling: If
Request[i] <= Need[i]andRequest[i] <= Available, pretend allocate and check safety.
-
-
-
Detection & Recovery:
-
Detection: Use Resource Allocation Graph (RAG) for single instance; wait-for graph for multiple. Periodic check for cycles.
-
Recovery: Process termination (all/one by one), resource preemption (victim selection, rollback).
-
-
[!TIP] Banker’s Algorithm is calculation-heavy. Always compute
Needmatrix first, then find safe sequence by finding a process whoseNeed <= Work(initiallyAvailable). UpdateWork = Work + Allocationafter "finishing" a process.
III. Memory Management
Memory Management Basics
-
Overlays: Only keep in memory the code/data needed at a given time. Used in large programs with limited memory. Programmer/compiler must manage overlay structure.
-
Swapping: Move entire process from main memory to backing store (disk) to free memory; later swapped back. Used in multiprogramming to increase degree of multiprogramming.
Contiguous Memory Allocation
-
Partitioning: Fixed partitions (internal fragmentation) or variable partitions (external fragmentation).
-
Compaction: OS moves processes in memory to create one large free block (only possible if relocation is dynamic).
-
Placement Algorithms:
-
First-Fit: Allocate first hole large enough. Fast.
-
Best-Fit: Allocate smallest hole large enough. Minimizes leftover space; slower.
-
Worst-Fit: Allocate largest hole. Aims to leave large leftover; generally poor.
-
-
Fragmentation:
-
Internal: Unused memory within allocated partition (fixed partitions).
-
External: Free memory exists but is non-contiguous (variable partitions).
-
Paging (High Frequency)
-
Concept: Divide physical memory into fixed-size frames (e.g., 4KB), logical memory into same-size pages. OS maintains page table per process:
Page # → Frame #. -
Address Translation: Logical address
(p, d)→ Physical address(f, d)wherepis page number,doffset. -
Translation Lookaside Buffer (TLB): Fast associative cache for page table entries. Hit ratio critical for performance.
- Effective Access Time (EAT):
EAT = (hit_ratio * TLB_access + (1-hit_ratio) * (TLB_access + 2*Memory_access))
- Effective Access Time (EAT):
-
Protection: Valid-Invalid bit in page table entry; invalid page → trap (segmentation fault).
-
Demand Paging: Bring pages into memory only when needed (on page fault). Lazy swapping.
-
Page Fault: Access to page not in memory.
-
Page Fault Service Time:
Service_time = Page_fault_rate * (Disk_access + Swap_in + Swap_out + Overhead)
-
Segmentation (High Frequency)
-
Concept: Divide logical address space into variable-sized segments (code, data, stack, heap) based on program structure.
-
Segment Table: Each entry has segment base (start physical address) and segment limit (length).
-
Advantages over Paging:
-
Natural view: Reflects programmer's view (modules).
-
Protection/Sharing: Share entire segment (e.g., code library).
-
No internal fragmentation (but external fragmentation exists).
-
-
Segmentation with Paging (Paged Segmentation): Each segment is paged (e.g., Intel x86). Combines benefits: logical segmentation + physical paging → no external fragmentation, easier allocation.
Virtual Memory (High Frequency)
-
Concept: Technique to give process illusion of large contiguous memory. Backed by disk. Implemented via demand paging or demand segmentation.
-
Benefits: More processes in memory, larger programs possible, I/O overhead reduced (only needed pages in memory).
-
Page Replacement Algorithms (High Frequency): When no free frame, choose victim page to replace.
-
FIFO: Replace oldest loaded page. Belady’s Anomaly: More frames → more page faults (possible for FIFO).
-
LRU (Least Recently Used): Replace page not used for longest time. Approximated by hardware (reference bits) or software (stack).
-
Optimal (OPT): Replace page whose next reference is farthest in future. Unrealistic (requires future knowledge), used for comparison.
-
Page Fault Calculation: Given reference string and frames, simulate algorithm, count unique page loads.
Example: Ref:
1,2,3,4,1,2,5,1,2,3,4,5with 3 frames.FIFO: Faults = 9; LRU: Faults = 8; OPT: Faults = 7.
-
Memory Management in UNIX & Windows
-
UNIX: Uses virtual memory with demand paging. Inode-based file system. Memory management via swap space and page replacement (modified clock algorithm). Kernel memory allocated via slab allocator.
-
Windows: Uses virtual address space per process (2GB user, 2GB kernel for 32-bit). Page file (
pagefile.sys) for backing store. Working set model: pages in physical memory. Combined demand paging & segmentation (segments for protection, paging for management).
IV. Storage Management: File Systems
File Concept
-
Attributes: Name, identifier, type, location, size, protection, time/date.
-
Operations: Create, delete, read, write, reposition (seek), truncate, open, close.
-
Types: Regular, directory, special (block/character).
-
Structures: Byte sequence (UNIX), record sequence (old systems), tree (Windows directories).
Access Methods
-
Sequential: Read next record (e.g., tape).
-
Direct (Random): Compute address of record
idirectly (e.g.,seek(i)). -
Indexed: Build index for each file; index block points to data blocks.
Directory Structure
-
Single-Level: All files in one directory → name clashes.
-
Two-Level: Master directory with user directories → solves name clashes, but no subdirectories.
DiagramCANVAS: Draw a tree: root → (user1_dir, user2_dir, ...) → files. -
Tree-Structured: Hierarchical; paths from root (
/). Current working directory. -
Acyclic Graph: Shared files/folders via links (hard/soft). Multiple parent directories.
DiagramCANVAS: Draw a DAG: two directories pointing to same file node. -
General Graph: Cycles possible → need garbage collection (UNIX links count).
-
Mount Points: Attach file system from one device to directory tree (e.g.,
/mnt).
File System Implementation
-
Partitioning: Disk divided into partitions (one per file system).
-
Boot Block: Initial program to boot OS.
-
Superblock: Contains file system metadata (size, block size, inode count, pointer to free blocks/inodes).
-
Inodes (UNIX): Data structure per file with metadata (owner, permissions, timestamps, pointers to data blocks). Indexed allocation (direct, single indirect, double indirect, triple indirect).
File Allocation Methods (High Frequency)
-
Contiguous: File occupies contiguous blocks. Fast sequential/direct access. External fragmentation, difficult to grow.
-
Linked: Each block has pointer to next. No external fragmentation, wasted space for pointers, slow direct access (must traverse).
-
Indexed: All pointers gathered in index block.
-
Single Indexed: Index block in memory; good for small files.
-
Multi-level Indexed: Chain of index blocks (UNIX inode). Supports large files.
-
Linked Indexed (FAT): File Allocation Table; array of next pointers; cluster chain. Fast traversal, FAT in memory.
-
File Protection
-
Access Control Lists (ACL): Per-file list of users/groups with permissions (rwx).
-
Capabilities: Special keys/tokens held by processes; presented to OS for access.
-
Passwords: File-level or user-level.
-
Encryption: File content encrypted with key.
Virtual File Systems (VFS)
-
Concept: Kernel layer providing common file model (open, read, write) to user space. VFS inode abstracts underlying file system (ext4, NTFS, NFS). Allows multiple file systems to be mounted and accessed uniformly.
-
Interface:
open(),read(),write(),close()→ dispatch to specific file system's methods.
File Systems in UNIX & Windows (High Frequency)
| Feature | UNIX (ext4) | Windows (NTFS) |
|---|---|---|
| Structure | Inode-based (fixed-size inode table). | Master File Table (MFT) entries (variable size). |
| Allocation | Extents (contiguous blocks) + multi-level indexed. | Clusters (contiguous on disk), B+ trees for directories. |
| Journaling | Yes (metadata journaling). | Yes (full metadata + data journaling optional). |
| Links | Hard links (same inode), Soft links (path pointers). | Hard links (same MFT record), Soft links (reparse points). |
| Permissions | User/Group/Others (rwx). | ACLs (more granular). |
| Performance | Generally faster for small files due to inode caching. | Better for large files, robust recovery. |
V. Storage Management: Disk Scheduling & Performance
Disk Structure & Performance Parameters
-
Tracks: Concentric circles on platter.
-
Sectors: Arc segments on track (typically 512B-4KB).
-
Cylinder: Set of tracks aligned vertically across platters.
-
Parameters:
-
Seek Time: Time to move head to target track. Dominant factor.
-
Rotational Latency: Time for desired sector to rotate under head. Avg = ½ rotation time.
-
Transfer Time: Time to read/write sector.
(sectors / rotation_rate). -
Access Time:
Seek Time + Rotational Latency + Transfer Time.
-
Disk Scheduling Algorithms (High Frequency)
-
FCFS: Requests in arrival order. Simple, but high seek time.
-
SSTF (Shortest Seek Time First): Select request closest to current head position. Reduces seek time, but starvation possible for far tracks.
-
SCAN (Elevator): Head moves in one direction servicing requests until end, then reverses. Fair, but long wait for requests just passed.
-
C-SCAN (Circular SCAN): Head moves in one direction servicing requests; when reaches end, jumps to beginning without servicing. More uniform wait than SCAN.
-
LOOK / C-LOOK: SCAN/C-SCAN but only goes as far as last request in direction, then reverses/jumps.
-
Calculation: Total Head Movement = sum of absolute differences between consecutive track requests (including initial head position).
[!TIP] Always draw Gantt-like chart for disk scheduling:
Head → Request1 → Request2 → .... Calculate total movement by summing|next_track - current_track|.
Disk Space Allocation
-
Contiguous: Fast sequential access, external fragmentation.
-
Linked: No external fragmentation, slow direct access.
-
Indexed: Balance; FAT is common (linked indexed).
Tape Organization
-
Sequential Access: Must wind through tape to reach data. Tape drives cheaper per GB, high capacity, but slow random access.
-
Tape Mounting: Physically mounting tape on drive; time-consuming. Used for backups/archiving.
VI. I/O Systems
I/O Hardware
-
Devices: Input (keyboard, mouse), Output (display, printer), I/O (disk, network).
-
Controllers: Interface between device and bus; has registers for commands/data.
-
Buses: Communication pathway (PCI, SATA, USB).
-
I/O Ports: Memory-mapped or special I/O instructions to access controller registers.
I/O Management
-
Logical Structure: User process → System Call Interface → Device Driver → Interrupt Handler → Device Controller → Device.
-
Kernel I/O Subsystem:
-
Scheduling: Order I/O requests (e.g., disk scheduling).
-
Buffering: Store data temporarily (to cope with speed mismatch).
-
Caching: Keep copies in faster memory.
-
Spooling: Overlap I/O of one job with computation of another (e.g., printing).
-
Device Allocation: Allocate devices, manage requests.
-
Error Handling: Retry, report failures.
-
I/O Operations
-
Synchronous I/O: Process issues request, blocks until I/O completes. Simple, but process idle.
-
Asynchronous I/O: Process issues request, continues execution, notified via interrupt/signal when done. Better for overlap.
-
Blocking vs Non-Blocking:
-
Blocking call: Caller waits for result.
-
Non-blocking call: Caller returns immediately; result later.
-
-
I/O Request Transfer: System call → kernel → device driver (queues request) → interrupt on completion → driver returns data → kernel returns to process.
I/O Buffering (High Frequency)
-
Purpose: Cope with device speed mismatch, block size differences, implement semantics (e.g.,
read()afterwrite()). -
Single Buffer: OS allocates one buffer in kernel. Process blocked until I/O to/from buffer completes. One buffer per I/O stream.
-
Double Buffering (Double Buffering): Two buffers; while one fills/empties for process, other fills/empties for device. Overlap I/O & computation.
-
Circular Buffer: Multiple buffers in ring;
nextandcurrentpointers. Used for streams (audio/video).
I/O in UNIX & Windows
-
UNIX: Device files in
/dev; read/write system calls for both files and devices (uniform interface). STREAMS for modular I/O. -
Windows: Device Drivers as kernel modules; Win32 API (
ReadFile,WriteFile) for files/devices; overlapped I/O for async; IOCTL for device-specific commands.
Special I/O Techniques
-
Interrupt-Driven I/O: Process issues I/O, blocks. Device controller performs I/O, interrupts CPU on completion. CPU switches to another process. Better CPU utilization than polling.
-
Concurrent I/O: Multiple I/O operations in progress simultaneously (via interrupts, DMA).
VII. Protection and Security
Security & Protection Mechanisms (High Frequency)
-
Goals:
-
Confidentiality: Prevent unauthorized disclosure.
-
Integrity: Prevent unauthorized modification.
-
Availability: Ensure service accessible to authorized users.
-
-
Principles:
-
Least Privilege: Give minimal necessary rights.
-
Fail-Safe Defaults: Default deny; explicit permission needed.
-
Economy of Mechanism: Keep design simple.
-
Complete Mediation: Check every access.
-
Open Design: Security should not depend on secrecy of design.
-
-
Authentication: Verify identity.
- Passwords, Biometrics, Tokens (smart cards), Multifactor.
-
Access Control:
- Access Matrix:
(object, subject)→ rights. Sparse → implement as Access Control Lists (ACL) (per-object list) or Capabilities (per-subject list/token).
- Access Matrix:
-
OS-Level Security Features:
-
User Accounts & Groups: Unique IDs, group IDs.
-
Permissions: rwx for user/group/others (UNIX); ACLs (Windows).
-
Encryption: File system encryption (EFS in Windows, ecryptfs in Linux).
-
Virus Protection: Antivirus scans, sandboxing.
-
Auditing: Log security events.
-
VIII. Distributed and Network Operating Systems
Network OS vs Traditional OS
-
Network OS (NOS): Extends OS to support networking.
-
Characteristics: Resource sharing (files, printers), communication (messages), user authentication across network, scalability.
-
Example: Windows Server with shared folders.
-
-
Traditional OS: Manages resources on a single machine; networking is optional/add-on.
Distributed OS vs Multiprocessor OS (High Frequency)
| Feature | Distributed OS | Multiprocessor OS (SMP) |
|---|---|---|
| Architecture | Network of independent nodes (loosely coupled). | Multiple CPUs sharing memory/bus (tightly coupled). |
| Communication | Message passing (high latency). | Shared memory (low latency). |
| Fault Tolerance | High (node failure isolated). | Low (CPU/memory failure crashes system). |
| Scalability | High (add nodes easily). | Limited (bus/memory bottleneck). |
| OS Structure | Each node has its own OS + middleware for transparency. | Single OS instance managing all CPUs. |
| Example | Cluster, Cloud OS. | Modern multi-core desktop/server OS. |
Remote File Access
-
NFS (Network File System): Sun RPC-based; stateless protocol; close-to-open consistency. Uses mount to integrate remote FS into local namespace.
-
SMB/CIFS (Server Message Block / Common Internet File System): Stateful; used by Windows for file/printer sharing. More features (locking, byte-range locks).
IX. System Calls
System Call Interface
-
Categories:
-
Process Control:
fork,exec,wait,exit,getpid. -
File Management:
open,read,write,close,lseek,stat,ioctl. -
Device Management:
ioctl,read,write(for devices). -
Information Maintenance:
gettimeofday,getpid,alarm. -
Communication:
pipe,shmget,msgsnd,socket. -
Protection:
chmod,chown,umask.
-
System Calls for Process Management (High Frequency)
-
fork(): Creates child process (duplicate of parent). Returns child PID to parent, 0 to child. -
exec()family (execl,execv): Replaces current process image with new program. -
wait()/waitpid(): Parent waits for child termination; gets exit status. -
exit(): Terminates process; releases resources. -
getpid(),getppid(): Get process/parent IDs. -
Typical Pattern:
fork()→exec()in child →wait()in parent.
System Calls for File Management (High Frequency)
-
open(path, flags, mode): Returns file descriptor (FD). Flags:O_RDONLY,O_WRONLY,O_RDWR,O_CREAT,O_APPEND. Mode: permissions (rwx). -
read(fd, buffer, count): Readscountbytes intobufferfrom filefd. Returns bytes read. -
write(fd, buffer, count): Writescountbytes frombufferto filefd. -
close(fd): Closes file descriptor; releases table entry. -
lseek(fd, offset, whence): Repositions file offset.whence:SEEK_SET,SEEK_CUR,SEEK_END. -
stat(path, &buf): Gets file metadata (size, timestamps, permissions) intobuf. -
ioctl(fd, request, argp): Device-specific control operations (e.g., get disk geometry).
[!TIP]
open()returns a small integer FD (0=stdin, 1=stdout, 2=stderr). All subsequent I/O uses this FD.read/writework on unstructured byte streams.
X. Advanced & Special Topics
Dynamic Linking and Loading
-
Static Linking: Library code copied into executable at compile/link time. Larger binaries, need relink for library updates.
-
Dynamic Linking: Library code not copied; references resolved at load time (load-time dynamic linking) or runtime (runtime dynamic linking via
dlopen/dlsym). -
Shared Libraries (DLL/.so): Single copy in memory, shared by multiple processes. Reduces memory usage, easier updates.
-
Load-time vs Runtime:
-
Load-time: OS loader links shared libs when program starts.
-
Runtime: Program explicitly loads/unloads libs during execution.
-
Virtual Concurrency vs Real Concurrency
-
Virtual Concurrency (Uniprocessor): Only one process/thread runs at any instant. OS time-slices CPU → illusion of parallelism.
-
Real Concurrency (Multiprocessor/Multicore): Multiple processes/threads truly execute simultaneously on different CPUs. Requires symmetric multiprocessing (SMP) OS with shared memory synchronization.
Resource Allocation Graph (RAG)
-
Purpose: Model for deadlock avoidance/detection.
-
Nodes: Processes (circles), Resources (squares; multiple instances shown as dots inside).
-
Edges:
-
Request Edge:
Process → Resource(process waiting for resource). -
Assignment Edge:
Resource → Process(resource allocated to process).
-
-
Deadlock: Cycle in RAG (for single-instance resources). For multiple instances, cycle is necessary but not sufficient; need detection algorithm (like Banker's).
Disk Mounting
-
Mounting: Integrating a file system from a storage device (partition) into the directory tree at a mount point (empty directory).
-
Unmounting: Detaching file system; ensures no open files.
-
Remote Mounting: Mounting file system from remote server (NFS, SMB). Transparent to user.
Interrupt Handling
-
Device signals interrupt (via controller).
-
CPU finishes current instruction, saves context (registers, PC) of interrupted process.
-
CPU jumps to interrupt handler (part of OS kernel) via interrupt vector table.
-
Handler determines source, services interrupt (e.g., reads data from controller register, copies to buffer).
-
Handler may wake blocked process waiting for I/O.
-
CPU restores saved context of interrupted process (or switches to ready process).
[!TIP] Interrupt-driven I/O allows CPU to do other work while I/O proceeds. DMA (Direct Memory Access) further reduces CPU overhead: device controller transfers data directly to/from memory without CPU intervention per byte.