Essential Operating Systems questions for technical and core fundamentals rounds. Covers 10–15% of typical interview weightage.
An Operating System (OS) is system software that manages hardware and software resources, providing services to programs. Main functions: Process Management (creation, scheduling, termination), Memory Management (allocation, deallocation, virtual memory), File System Management (organize and access files), Device Management (I/O device control via drivers), Security & Access Control, and User Interface (CLI/GUI). Examples: Linux, Windows, macOS, Android. The OS acts as an intermediary between user applications and hardware.
A Process is an independent program in execution with its own memory space (code, data, heap, stack, PCB). Processes are isolated — one cannot directly access another's memory. A Thread is a lightweight unit of execution within a process, sharing the process's memory (code, data, heap) but having its own stack and registers. Threads within a process communicate easily via shared memory; processes use IPC (pipes, sockets, shared memory, message queues). Thread creation is faster (~10x) than process creation. Multithreading enables parallelism within a single application.
Process States (lifecycle): New → Ready (in memory, waiting for CPU) → Running (executing) → Waiting/Blocked (waiting for I/O or event) → Terminated. Process Control Block (PCB): data structure maintaining all process information — Process ID, Process State, Program Counter, CPU registers, CPU scheduling info (priority, queue pointers), Memory management info (page tables), I/O status (open files, I/O devices), Accounting info (CPU time used). The OS uses the PCB during context switching to save and restore process state.
CPU Scheduling selects which process in the ready queue gets CPU time. Key metrics: CPU utilization, throughput, turnaround time, waiting time, response time. Algorithms: FCFS (First Come First Served) — non-preemptive, convoy effect. SJF (Shortest Job First) — optimal average waiting time, requires future knowledge. SRTF — preemptive SJF. Round Robin — time quantum, best for time-sharing, high context switch overhead. Priority Scheduling — starvation issue (solved by aging). Multilevel Queue — multiple queues for different process types. Modern OS: uses Multilevel Feedback Queue.
A Deadlock occurs when a set of processes are blocked forever, each waiting for a resource held by another process in the set. Four necessary conditions (Coffman Conditions — ALL must hold simultaneously):
1) Mutual Exclusion — resources are non-shareable.
2) Hold and Wait — process holds resources while waiting for others.
3) No Preemption — resources cannot be forcibly taken.
4) Circular Wait — circular chain of processes waiting for each other. Prevention: negate one condition. Avoidance: Banker's Algorithm. Detection: Resource Allocation Graph. Recovery: process termination or resource preemption.
Banker's Algorithm is a deadlock avoidance algorithm that simulates resource allocation to ensure the system stays in a safe state. Concepts: Maximum (max resources each process may need), Allocation (currently allocated), Need (maximum - allocation), Available (free resources). Safety Algorithm: Find a process whose Need ≤ Available, execute it, release its resources, repeat for all processes. If all processes complete, system is in safe state. Limitation: requires knowing maximum resource needs in advance and is computationally expensive for large systems.
Paging divides physical memory into fixed-size frames and logical memory into same-size pages. The OS maintains a Page Table for each process. Eliminates external fragmentation but causes internal fragmentation. Page size typically 4KB. Segmentation divides memory into variable-size segments based on logical divisions (code, stack, heap, data). Maintains a Segment Table with base and limit registers. Eliminates internal fragmentation but causes external fragmentation. Segmented Paging combines both: memory divided into segments, each segment paged — used in x86 architecture.
Virtual Memory allows processes to use more memory than physically available by using disk space (swap space/page file) as an extension of RAM. Mechanism: Demand Paging — pages loaded into memory only when needed. When a process accesses a page not in memory, a Page Fault occurs — OS loads the page from disk, which is expensive (milliseconds vs nanoseconds). Page Replacement Algorithms: FIFO (simple, Belady's Anomaly), LRU (Least Recently Used — best practical), Optimal (theoretical best, impossible in practice). Thrashing: excessive paging when working set > available frames.
Internal Fragmentation: wasted space inside an allocated memory block. Occurs in fixed-size allocation (paging, fixed-partition schemes) when allocated block is larger than needed. Example: process needs 18KB but gets a 20KB frame — 2KB wasted internally. External Fragmentation: total free memory is sufficient but scattered in non-contiguous blocks, making it unusable for a large request. Occurs in variable-size allocation (segmentation, dynamic partitioning). Solutions: compaction (defragmentation, expensive), coalescing free blocks, using buddy system.
Semaphore is a synchronization variable with two operations: wait (P) — decrement; if negative, block the process. signal (V) — increment; if processes waiting, wake one up. Binary Semaphore (0/1) acts like a mutex. Counting Semaphore allows multiple concurrent access (value = number of available resources). Mutex (Mutual Exclusion Lock): specifically designed for mutual exclusion — only the thread that locked it can unlock it (ownership). Semaphore can be signaled by any thread (no ownership). Mutex is preferred for critical section protection; semaphores for resource counting and producer-consumer synchronization.
Classic synchronization problem: Producers generate data placed in a bounded buffer; Consumers remove and process data. Problem: prevent producer from adding to full buffer, consumer from removing from empty buffer, and concurrent access conflicts. Solution using semaphores: mutex (binary, for mutual exclusion), empty (counting, tracks empty slots — initialized to buffer size), full (counting, tracks filled slots — initialized to 0). Producer: wait(empty) → wait(mutex) → add item → signal(mutex) → signal(full). Consumer: wait(full) → wait(mutex) → remove item → signal(mutex) → signal(empty).
A Context Switch is the process of saving the state of the currently running process/thread and restoring the state of the next scheduled process/thread. Saved state includes: program counter, CPU registers, stack pointer, page table pointer (stored in PCB). Costs: direct — time to save/restore state (microseconds). Indirect — cache pollution (new process's memory not in cache, causing cache misses). Thread context switches are cheaper than process switches because threads share memory space (no TLB flush needed for same-process threads). Modern OS minimizes context switches via efficient scheduling.
IPC enables processes to communicate and synchronize. Methods:
1) Shared Memory — fastest IPC; processes map the same memory region; requires synchronization.
2) Message Passing — processes send/receive messages via OS; safe but slower.
3) Pipes — unidirectional byte stream; anonymous pipes for parent-child; named pipes (FIFOs) for unrelated processes.
4) Sockets — network communication; works across machines.
5) Signals — asynchronous notifications (SIGKILL, SIGTERM).
6) Memory-mapped files. Rule: shared memory for speed-critical same-machine communication; sockets for distributed systems.
Thrashing occurs when a process spends more time paging (swapping pages in/out of memory) than executing. Cause: insufficient physical memory for the working set of all active processes — OS keeps page faulting. Effect: CPU utilization drops dramatically, system appears unresponsive. Prevention: Working Set Model — track the set of pages a process actively uses; allocate enough frames for the working set. Page Fault Frequency (PFF) — monitor fault rate; if too high, allocate more frames; if too low, reclaim frames. Solutions: add more RAM, reduce multiprogramming degree, use better page replacement policies.
File Allocation Methods determine how files are stored on disk:
1) Contiguous Allocation — file occupies consecutive blocks. Fast sequential access, easy random access. Suffers external fragmentation, difficult to grow files.
2) Linked Allocation — each block contains pointer to next block. No fragmentation, easy to grow. Poor random access O(n), pointer overhead, reliability risk (broken pointer).
3) Indexed Allocation — index block contains all block pointers. Supports both sequential and random access. UNIX i-node: direct blocks + single/double/triple indirect blocks for large files. FAT (File Allocation Table): linked list-like, stored in table for faster access.
Preemptive Scheduling: OS can forcibly remove CPU from a running process (e.g., when a higher-priority process arrives or time quantum expires). Examples: Round Robin, SRTF, Priority (preemptive). Advantages: better responsiveness, ensures fairness. Disadvantages: more context switches, race conditions in critical sections. Non-Preemptive Scheduling: once a process gets CPU, it runs until it completes or voluntarily gives up CPU (I/O wait). Examples: FCFS, SJF, Priority (non-preemptive). Advantages: simpler, no preemption-related race conditions. Disadvantages: poor responsiveness, convoy effect with long processes.
System Calls are the interface between user-space applications and the OS kernel. They provide controlled access to hardware and OS services. Types: Process Control (fork, exec, exit, wait), File Management (open, read, write, close), Device Management (ioctl), Information Maintenance (getpid, time), Communication (socket, send, recv). Mechanism:
1) User program calls library function (e.g., read()).
2) Library sets up system call number and arguments in registers.
3) Software interrupt/trap instruction switches to kernel mode.
4) Kernel executes the requested service.
5) Returns to user mode with result. Mode switch is expensive — minimize unnecessary system calls.
Dual-mode operation protects the OS from errant user programs. User Mode: restricted execution environment; cannot directly access hardware or privileged instructions; memory access limited to process's own space. Kernel Mode (Privileged/Supervisor Mode): full access to hardware, memory, and privileged instructions; OS kernel runs here; can execute any instruction. Mode switch happens via: system calls (user → kernel), interrupts (I/O completion, timer), exceptions (page fault, division by zero). After handling, returns to user mode. Violation of user-mode restrictions causes segmentation fault or access violation.
A Race Condition occurs when multiple threads/processes access shared data concurrently and the outcome depends on the execution order. Example: two threads simultaneously incrementing a counter — both read the same value, increment, and write back, losing one increment. Prevention requires synchronization: Mutex Locks — only one thread in critical section at a time. Semaphores — general synchronization. Atomic Operations — hardware-supported indivisible operations (compare-and-swap). Lock-free data structures — using atomic CAS operations. Critical Section: identify the code section that must be atomic and protect it with the minimal lock scope necessary.
Buffering: temporarily storing data in memory (buffer) while transferring between two devices or between a device and an application. Smooths out speed differences between producer and consumer. Single buffer, Double buffer, Circular buffer. Spooling (Simultaneous Peripheral Operations On-Line): stores jobs in a spool (queue on disk) to be processed by a slow device (e.g., printer). Multiple programs can 'print' simultaneously — jobs queued, printed one by one. Examples: print spooler (CUPS), email queuing, batch job queuing. Difference: buffering is in-memory for a single job; spooling uses disk for multiple jobs queued for a device.