Operating system interviews test your understanding of how hardware and software interact — from process scheduling and memory allocation to deadlock prevention and file systems. This guide covers the 50 most common OS questions with concise, accurate answers.
Quick reference
| Topic | Key concepts |
|---|---|
| Processes & Threads | PCB, states, context switch, fork/exec |
| Scheduling | FCFS, SJF, Round Robin, Priority, MLFQ |
| Synchronization | Mutex, semaphore, monitor, deadlock |
| Memory | Paging, segmentation, virtual memory, TLB |
| Page Replacement | FIFO, LRU, Optimal, Clock |
| File Systems | Inodes, FAT, NTFS, ext4, journaling |
| I/O | Interrupts, DMA, buffering, RAID |
| Kernel | Monolithic, microkernel, system calls |
Processes and Threads
1. What is a process? How does it differ from a program?
A program is a passive set of instructions stored on disk. A process is a running instance of a program — it includes:
- Program code (text segment)
- Stack (function calls, local variables)
- Heap (dynamically allocated memory)
- Data segment (global/static variables)
- Process Control Block (PCB) — OS metadata
You can run the same program as multiple processes simultaneously (e.g., two terminal windows running bash).
2. What is a Process Control Block (PCB)?
The PCB is the OS data structure that stores all information about a process:
| PCB field | Contents |
|---|---|
| Process ID (PID) | Unique identifier |
| Process state | New, Ready, Running, Waiting, Terminated |
| Program counter | Address of next instruction |
| CPU registers | Snapshot of all registers |
| Memory limits | Base/limit registers, page table pointer |
| Open files | File descriptor table |
| I/O status | Pending I/O requests |
| Scheduling info | Priority, CPU time used |
| Parent PID | For process hierarchy (Unix) |
3. What are the process states?
fork()
|
[New] ──────────────────────────────────────────────►
| admitted
[Ready] ◄──────────────────── [Waiting]
| I/O complete/event |
scheduled | I/O or event wait
| |
[Running] ──────────────────►
| interrupt (preempt) ──► [Ready]
| exit
[Terminated]
| State | Description |
|---|---|
| New | Process is being created |
| Ready | Waiting to be assigned CPU |
| Running | Currently executing on CPU |
| Waiting/Blocked | Waiting for I/O or event |
| Terminated | Finished execution |
4. What is a thread? How does it differ from a process?
A thread is the smallest unit of CPU execution within a process. Multiple threads share the same process address space.
| Aspect | Process | Thread |
|---|---|---|
| Memory | Separate address space | Shared address space |
| Resources | Own file descriptors, heap | Shared (own stack only) |
| Creation cost | High (fork + copy) | Low |
| Communication | IPC (pipes, shared mem) | Direct (shared vars) |
| Crash isolation | One process crash ≠ others | Thread crash can kill process |
| Switching | Expensive (full context) | Cheaper (same page tables) |
5. What is context switching?
Context switching is the OS saving the state of the current process/thread and restoring another's state so the CPU can run a different process.
Steps:
- Save running process's registers → PCB
- Update PCB state (Running → Ready or Waiting)
- Choose next process (scheduler)
- Load new process's registers from its PCB
- Update memory mappings (flush TLB if different process)
- Resume execution at saved program counter
Cost: Pure overhead — no useful work done. Minimised with thread pools and cooperative scheduling.
6. What is the difference between fork() and exec()?
| System call | What it does |
|---|---|
fork() |
Creates a copy of the current process (child). Child gets a copy of parent's address space (copy-on-write). Returns 0 in child, child PID in parent. |
exec() |
Replaces the current process image with a new program. Same PID, new code/data/stack. |
| Combined | Shell: fork() then exec() in child to run a new command while parent waits. |
7. What is a zombie process? A daemon?
Zombie process: A process that has finished executing but its entry remains in the process table because the parent hasn't called wait() yet. The OS holds exit status until parent reads it.
# View zombies
ps aux | grep Z
Daemon: A background process that runs without a controlling terminal (e.g., sshd, cron). Created by double-forking and closing stdin/stdout/stderr.
8. What is inter-process communication (IPC)?
IPC mechanisms for processes to exchange data:
| Mechanism | Description | Use case |
|---|---|---|
| Pipes | Unidirectional byte stream | Parent ↔ child |
| Named pipes (FIFOs) | Like pipes but filesystem-accessible | Unrelated processes |
| Message queues | Structured messages, kernel-managed | Decoupled producers/consumers |
| Shared memory | Fastest IPC; processes map same physical pages | High-performance data sharing |
| Semaphores | Synchronization signals | Protect shared memory |
| Sockets | Network or Unix domain | Distributed or local IPC |
| Signals | Async notifications | SIGTERM, SIGKILL, SIGUSR1 |
9. What is the difference between user mode and kernel mode?
| Mode | Privilege | Access |
|---|---|---|
| User mode | Ring 3 (x86) | Can't access hardware, can't run privileged instructions |
| Kernel mode | Ring 0 (x86) | Full hardware access, all instructions allowed |
Transition happens via system calls (software interrupt, syscall instruction) — the only safe gateway from user to kernel mode.
10. What is a system call?
A system call is the interface between a user-space program and the OS kernel. When a process needs a privileged operation:
- User program calls library function (e.g.,
read()) - Library puts arguments in registers, executes
syscallinstruction - CPU switches to kernel mode, jumps to syscall handler
- Kernel performs operation (validates permissions, accesses hardware)
- Returns result, CPU switches back to user mode
Examples: open, read, write, close, fork, exec, mmap, socket, exit.
CPU Scheduling
11. What is CPU scheduling? Why is it needed?
CPU scheduling determines which ready process/thread gets the CPU next. Needed because CPU is a scarce resource and multiple processes compete for it.
Goals:
- Maximise CPU utilisation
- Maximise throughput (processes completed per unit time)
- Minimise turnaround time (submission to completion)
- Minimise waiting time (time in ready queue)
- Minimise response time (first response)
- Fairness
12. What are the main CPU scheduling algorithms?
| Algorithm | Description | Preemptive? | Pros | Cons |
|---|---|---|---|---|
| FCFS | Run in arrival order | No | Simple | Convoy effect — short jobs stuck behind long |
| SJF | Shortest job first | No | Optimal avg wait | Requires burst time prediction; starvation |
| SRTF | Shortest remaining time first | Yes | Optimal avg wait | High overhead; starvation |
| Round Robin | Fixed time quantum, circular | Yes | Fair, good response time | High context switch if quantum too small |
| Priority | Highest priority runs first | Both | Flexible | Starvation (fix: aging — increase priority over time) |
| MLFQ | Multiple queues with different priorities | Yes | Adaptive | Complex tuning |
13. What is the difference between preemptive and non-preemptive scheduling?
| Type | Description |
|---|---|
| Non-preemptive | Once a process gets the CPU, it runs until it voluntarily releases (I/O or terminates). Simple but poor for interactive systems. |
| Preemptive | OS can forcibly take CPU away (timer interrupt). Required for real-time and interactive systems. |
14. What is Round Robin scheduling? How do you choose the quantum?
Round Robin (RR): Each process gets a fixed time quantum (e.g., 10–100ms). If not done, it's preempted and added to the back of the ready queue.
Quantum selection:
- Too small: Excessive context switching overhead
- Too large: Degenerates to FCFS
- Rule of thumb: 80% of CPU bursts should be shorter than the quantum
15. What is the Multilevel Feedback Queue (MLFQ)?
MLFQ has multiple queues with decreasing priority. New processes start at the highest-priority queue (shortest quantum). If a process uses its full quantum, it's demoted to a lower queue (longer quantum). I/O-bound processes that give up CPU early stay at high priority.
Solves starvation with periodic priority boost — move all processes to the top queue after some time interval.
Synchronization and Deadlocks
16. What is a race condition?
A race condition occurs when two or more processes access shared data concurrently and the final result depends on the execution order. The shared section where this can happen is the critical section.
Thread A: balance = balance + 100 (reads 500, adds 100)
Thread B: balance = balance - 200 (reads 500, subtracts 200)
Result: 600 or 300 — depends on timing. Correct: 400.
17. What are the requirements for a critical section solution?
Any solution to the critical section problem must satisfy:
- Mutual exclusion: Only one process in the critical section at a time
- Progress: If no process is in the critical section, a process that wants to enter must be able to (no indefinite postponement)
- Bounded waiting: A limit exists on the number of times other processes can enter before a waiting process is allowed in
18. What is a mutex? A semaphore? How do they differ?
| Feature | Mutex | Semaphore |
|---|---|---|
| Type | Binary lock (0 or 1) | Counter (0 to N) |
| Ownership | Only the locking thread can unlock | Any thread can signal |
| Use case | Mutual exclusion | Resource counting + signaling |
| Variants | Recursive mutex, spinlock | Binary, counting |
Mutex example:
pthread_mutex_lock(&mutex);
// critical section
pthread_mutex_unlock(&mutex);
Semaphore operations:
wait(S)/P(S): Decrement S; if S < 0, blocksignal(S)/V(S): Increment S; wake a blocked process
19. What is a monitor?
A monitor is a higher-level synchronization construct (built into languages like Java):
- Only one thread executes inside the monitor at a time
- Condition variables:
wait()releases the lock and blocks;notify()/notifyAll()wakes waiting threads - Prevents many common mutex mistakes (forgetting to unlock, signaling wrong condition)
synchronized (lock) {
while (!condition) lock.wait();
// critical section
lock.notifyAll();
}
20. What are the four necessary conditions for deadlock?
All four must hold simultaneously:
| Condition | Description |
|---|---|
| Mutual exclusion | At least one resource is non-shareable (only one process at a time) |
| Hold and wait | A process holds at least one resource and waits for more |
| No preemption | Resources cannot be forcibly taken; only released voluntarily |
| Circular wait | P1 waits for P2, P2 waits for P3, …, Pn waits for P1 |
21. How can deadlocks be handled?
| Strategy | Description |
|---|---|
| Prevention | Eliminate at least one of the 4 conditions (e.g., require all resources upfront → no hold-and-wait) |
| Avoidance | Use Banker's Algorithm to only grant requests if the system stays in a safe state |
| Detection & Recovery | Allow deadlocks, detect via resource allocation graph, then break by terminating or preempting processes |
| Ostrich Algorithm | Ignore the problem (used in practice by most OSes; deadlocks are rare enough) |
22. Explain the Banker's Algorithm.
The Banker's Algorithm (Dijkstra) prevents deadlock by checking if a resource grant leaves the system in a safe state — one where every process can eventually complete in some order.
State: n processes, m resource types
For each request:
1. Check request ≤ need[i] (no over-requesting)
2. Check request ≤ available (resources exist)
3. Tentatively allocate
4. Run safety algorithm:
- Find process whose need ≤ available
- Simulate completion, release resources
- Repeat until all done (safe) or stuck (unsafe)
5. If safe → grant; if unsafe → make process wait
23. What is the difference between starvation and deadlock?
| Deadlock | Starvation | |
|---|---|---|
| Definition | Circular wait — all processes blocked forever | A process waits indefinitely while others proceed |
| Root cause | Circular dependency on resources | Scheduling policy (low priority never runs) |
| Fix | Break deadlock (terminate/preempt) | Aging — increase priority over time |
24. What is a spinlock?
A spinlock is a busy-waiting lock: the thread continuously checks (spins) if the lock is free instead of blocking.
Pros: No context switch overhead; fast if lock is held briefly
Cons: Wastes CPU cycles; bad when lock held for long duration
Use case: Kernel code where sleeping is not allowed; multi-core systems with short critical sections
Memory Management
25. What is memory management? What are its goals?
Memory management is the OS function of allocating, tracking, and reclaiming RAM.
Goals:
- Allocate memory to processes
- Protect one process's memory from others
- Allow more processes than physical RAM (virtual memory)
- Efficient space utilisation (avoid fragmentation)
26. What is the difference between contiguous and non-contiguous memory allocation?
| Type | Description | Problem |
|---|---|---|
| Contiguous | Process occupies one continuous block of RAM | External fragmentation |
| Non-contiguous | Process split into chunks placed anywhere | Needs translation mechanism (paging/segmentation) |
Fragmentation types:
- Internal: Allocated block larger than needed (wasted inside block)
- External: Enough total free space but not contiguous
27. What is paging?
Paging divides:
- Physical memory into fixed-size frames
- Process virtual address space into same-size pages
OS maintains a page table per process mapping page numbers to frame numbers.
Virtual address: [page number | offset]
Physical address: [frame number | offset]
^ from page table
Benefits: Eliminates external fragmentation; enables non-contiguous allocation.
28. What is segmentation?
Segmentation divides a process's address space into logical units (segments: code, data, stack, heap) of variable size.
Each segment has a base (physical start address) and limit (size).
Comparison:
| Paging | Segmentation | |
|---|---|---|
| Division | Fixed size (pages) | Variable size (segments) |
| Fragmentation | Internal | External |
| Logical meaning | None | Matches program structure |
| Protection | Per-page bits | Per-segment bits |
Many architectures combine both (segmented paging).
29. What is virtual memory?
Virtual memory allows processes to use more memory than physical RAM by storing inactive pages on disk (swap space).
Each process sees a large, contiguous virtual address space. The OS transparently moves pages between RAM and disk.
Benefits:
- Run programs larger than RAM
- More processes in memory simultaneously
- Memory isolation between processes
Cost: Disk access is ~1000× slower than RAM — excessive paging causes thrashing.
30. What is a TLB (Translation Lookaside Buffer)?
The TLB is a hardware cache for page table entries, located in the CPU.
Without TLB: every memory access = 2+ memory accesses (page table lookup + actual data).
With TLB: most accesses = 1 memory access (TLB hit).
TLB miss: Hardware (or OS) walks the page table and loads the entry into TLB.
TLB flush: On context switch to a different process (different page table) — all TLB entries invalidated (or tagged with Address Space IDs/ASIDs to avoid full flush).
Typical TLB hit rate: 95–99% → effective memory access time ≈ 1.01–1.05× RAM speed.
31. What are page replacement algorithms?
When a page fault occurs and no free frame exists, the OS must evict a page.
| Algorithm | Strategy | Optimal? | Belady's anomaly? |
|---|---|---|---|
| FIFO | Evict oldest loaded page | No | Yes — more frames can cause more faults |
| Optimal (OPT) | Evict page used furthest in the future | Yes (theoretical) | No |
| LRU | Evict least recently used page | Near-optimal | No |
| Clock (Second Chance) | FIFO + reference bit; give pages a second chance | Good approximation of LRU | No |
| LFU | Evict least frequently used | No | No |
LRU approximation (hardware reference bit): On access, set reference bit = 1. On replacement, choose page with bit = 0; periodically clear all bits.
32. What is thrashing?
Thrashing occurs when a process spends more time handling page faults than executing:
- Too many processes loaded → each has too few frames
- Working sets don't fit in RAM → constant page faults
- High paging I/O → CPU utilisation drops
- OS loads more processes (to increase CPU use) → makes it worse
Solutions:
- Working set model: Track active pages per process; only load process if its working set fits
- Page fault frequency: Reduce degree of multiprogramming when fault rate too high
- Increase RAM
33. What is memory-mapped I/O vs port-mapped I/O?
| Type | Description |
|---|---|
| Memory-mapped I/O | Device registers appear at specific memory addresses. Normal load/store instructions access them. Used in most modern CPUs (x86-64, ARM). |
| Port-mapped I/O | Separate I/O address space. Special in/out instructions on x86. |
File Systems
34. What is an inode?
An inode (index node) is a data structure in Unix file systems storing file metadata:
| Inode field | Content |
|---|---|
| File type | Regular, directory, symlink, device |
| Permissions | rwxrwxrwx (user/group/other) |
| Hard link count | Number of directory entries pointing here |
| Owner UID/GID | Numeric user and group IDs |
| Size | In bytes |
| Timestamps | atime/mtime/ctime |
| Block pointers | Direct (12), single indirect, double indirect, triple indirect |
Note: Inodes do NOT store the filename — filenames are in directory entries.
35. What is the difference between a hard link and a soft (symbolic) link?
| Hard link | Soft (symbolic) link | |
|---|---|---|
| Points to | Same inode (same data) | Path string to target |
| Cross-filesystem | No (same filesystem only) | Yes |
| Target deleted | Data still accessible | Broken (dangling symlink) |
| Size | Same as original | Size of path string |
| Directories | Not allowed (prevents loops) | Allowed |
36. What are common file system types?
| File system | OS | Key features |
|---|---|---|
| ext4 | Linux | Journaling, extents, 1 exabyte volumes |
| NTFS | Windows | ACLs, encryption, compression, journaling |
| FAT32 | Cross-platform | Simple, wide compatibility, no permissions, 4 GB file limit |
| exFAT | Cross-platform | FAT32 successor, no 4 GB limit, for flash drives |
| APFS | macOS/iOS | Copy-on-write, snapshots, encryption |
| XFS | Linux | High performance, large files, journaling |
| ZFS | Linux/FreeBSD | Copy-on-write, snapshots, RAID-Z, data integrity |
| Btrfs | Linux | Copy-on-write, snapshots, RAID |
37. What is journaling in file systems?
Journaling maintains a log (journal) of changes before committing them to the main file system. Prevents corruption on crash:
- Write changes to journal (fast, sequential)
- Commit journal entry
- Apply changes to file system
- Clear journal entry
On crash recovery, replay incomplete journal entries to restore consistency — much faster than checking entire file system (like fsck).
Journal modes (ext4):
writeback: Only metadata journaled (fastest, some data risk)ordered: Data written before metadata journaled (default; good balance)journal: Both data and metadata journaled (safest, slowest)
38. What is RAID?
RAID (Redundant Array of Inexpensive Disks) combines multiple disks for performance or redundancy:
| Level | Description | Min disks | Redundancy | Performance |
|---|---|---|---|---|
| RAID 0 | Striping | 2 | None — lose any disk = lose all data | Best read/write |
| RAID 1 | Mirroring | 2 | 1 disk failure | Good read, normal write |
| RAID 5 | Striping + distributed parity | 3 | 1 disk failure | Good read, slower write |
| RAID 6 | Striping + 2 parity | 4 | 2 disk failures | Good read, slower write |
| RAID 10 | Mirror + stripe | 4 | 1 disk per mirror pair | Best of 1 and 0 |
Virtual Memory and I/O
39. What is demand paging?
Demand paging loads pages into RAM only when they are first accessed (on page fault), not all at once at process start.
Page fault handling:
- CPU references page not in memory → hardware raises page fault trap
- OS checks if access is valid (check page table, address space)
- Find a free frame (or evict a page)
- Load requested page from disk into frame
- Update page table: set present bit = 1
- Restart the faulting instruction
40. What is copy-on-write (COW)?
After fork(), instead of copying the entire parent's address space, the child and parent share the same physical pages marked read-only. When either process writes to a page:
- Page fault triggered
- OS creates a private copy of that page for the writing process
- Both processes now have separate copies
Benefit: fork() + exec() is very fast (exec replaces address space immediately; most pages never copied).
41. What is DMA (Direct Memory Access)?
DMA allows I/O devices to transfer data directly to/from RAM without CPU intervention:
- CPU programs DMA controller with source, destination, size
- CPU returns to other work
- DMA controller transfers data between device and memory
- DMA raises interrupt when complete
- CPU processes interrupt, checks results
Without DMA: CPU must copy each byte → wastes CPU cycles on I/O.
42. What is an interrupt? How does interrupt handling work?
An interrupt is a signal to the CPU that an event requires immediate attention.
Types:
- Hardware interrupts: Keyboard press, NIC packet received, disk I/O complete
- Software interrupts (traps): System calls, exceptions (division by zero, page fault)
Handling:
- CPU finishes current instruction
- Saves current context (PC, registers, flags)
- Looks up handler in Interrupt Descriptor Table (IDT)
- Jumps to interrupt service routine (ISR) in kernel mode
- ISR handles the event
- Restores context, resumes interrupted process
Kernel Types and Boot
43. What are kernel types?
| Type | Description | Examples |
|---|---|---|
| Monolithic | All OS services in kernel space; fast but large | Linux, traditional Unix, Windows NT |
| Microkernel | Minimal kernel (IPC, memory, scheduling); services run in user space | Mach, MINIX, QNX, seL4 |
| Hybrid | Monolithic with some microkernel principles | macOS (XNU), Windows NT (partially) |
| Exokernel | Minimal protection; applications manage resources directly | Research systems |
Trade-off: Monolithic = faster (no context switch between services). Microkernel = more secure/reliable (service crash doesn't crash kernel).
44. What happens during the OS boot process?
- Power on → CPU starts in real mode, jumps to firmware (BIOS/UEFI)
- POST (Power-On Self Test) — hardware check
- Boot device — firmware finds bootable device (MBR/GPT)
- Bootloader (GRUB, Windows Boot Manager) — loads kernel from disk
- Kernel initialisation — sets up memory, interrupts, scheduler
- Init process — kernel launches PID 1 (
systemd/init) in user space - Services start —
systemdstarts daemons, mounts filesystems - Login prompt — display manager or TTY login
45. What is the difference between 32-bit and 64-bit addressing?
| 32-bit | 64-bit | |
|---|---|---|
| Address space | 2³² = 4 GB per process | 2⁶⁴ = 16 EB theoretical (128 TB practical) |
| Max RAM | ~3.5 GB usable (kernel reserves some) | Terabytes |
| Register width | 32 bits | 64 bits (double precision operations, larger pointers) |
| Current use | Legacy embedded, old systems | All modern desktops/servers |
Advanced Topics
46. What is process scheduling in multi-core systems?
Challenges unique to multi-core:
| Challenge | Description |
|---|---|
| Load balancing | Distribute processes evenly across cores (push/pull migration) |
| Cache affinity | Keep process on same core — its data is already in that core's cache |
| NUMA | Non-Uniform Memory Access — memory closer to some cores; prefer local allocation |
| Hyperthreading | One physical core runs 2 hardware threads; share execution units |
Affinity scheduling: Prefer to reschedule process on the core that last ran it. Improves cache hit rate.
47. What are the different types of kernels threads vs user threads?
| User-level threads | Kernel-level threads | |
|---|---|---|
| Managed by | Thread library (user space) | Kernel |
| Context switch | Fast (no syscall) | Slow (syscall) |
| Blocking I/O | Blocks entire process | Only blocks that thread |
| Parallelism | Limited to 1 core (M:1 mapping) | True multi-core parallelism |
| Example | Green threads, coroutines | pthreads, Java threads on Linux |
Modern systems use M:N mapping (many user threads → pool of kernel threads) for the best of both worlds.
48. What is virtual memory segfault vs stack overflow?
| Error | Cause |
|---|---|
| Segmentation fault (SIGSEGV) | Process accesses memory it doesn't own — invalid pointer, null dereference, buffer overflow into protected page |
| Stack overflow | Stack grows too large (unbounded recursion, huge local arrays) — hits the stack guard page, triggers SIGSEGV |
The OS sends SIGSEGV (signal 11) to the process, which typically terminates it with a core dump.
49. What is the difference between swapping and paging?
| Swapping | Paging | |
|---|---|---|
| Unit | Entire process | Individual pages (4 KB) |
| Granularity | Coarse | Fine |
| Speed | Slow (large I/O) | Faster (small transfers) |
| Modern use | Rarely used (too slow) | Universal in modern OSes |
Modern OSes use paging + swap (page-level swapping) — individual pages are swapped, not whole processes.
50. What is the producer-consumer problem? How do you solve it?
Classic synchronization problem: Producers add items to a shared buffer; consumers remove them. Buffer has finite size.
Requirements:
- Producers wait when buffer is full
- Consumers wait when buffer is empty
- No race conditions on buffer access
Solution using semaphores:
semaphore mutex = 1; // mutual exclusion for buffer
semaphore empty = N; // count of empty slots (initially N)
semaphore full = 0; // count of full slots (initially 0)
// Producer
wait(empty); // wait for empty slot
wait(mutex); // lock buffer
add_item(buffer);
signal(mutex); // unlock
signal(full); // notify consumer
// Consumer
wait(full); // wait for item
wait(mutex); // lock buffer
remove_item(buffer);
signal(mutex); // unlock
signal(empty); // notify producer
Order matters: Always wait the counting semaphore before the mutex to avoid deadlock.
Common mistakes
| Mistake | Correct understanding |
|---|---|
| "Threads are faster than processes" | Threads have less overhead to create/switch, but code structure matters more |
| "LRU is always best" | Optimal (OPT) is theoretically best; LRU is a good approximation |
| "More RAM always prevents thrashing" | Depends on working sets; scheduling adjustments also needed |
| "fork() copies all memory" | Copy-on-write — pages shared until written |
| "Deadlock requires 3+ processes" | Deadlock can occur with just 2 processes |
| "Preemptive = better" | Non-preemptive is simpler and better for batch systems |
| "Page fault = crash" | Page faults are normal; they load pages from swap. Only invalid accesses crash. |
| "Kernel mode = admin privileges" | Kernel mode is a CPU privilege level; admin/root is a software permission concept |
OS vs related fields
| Field | Focus | Overlap with OS |
|---|---|---|
| Computer Architecture | CPU design, instruction sets, caches | OS uses hardware features (TLB, rings, DMA) |
| Networks | Protocols, routing, sockets | OS provides socket API, network stack in kernel |
| Database Systems | Transactions, ACID, storage engines | OS provides file I/O, memory mapping, processes |
| Distributed Systems | Consistency, availability, partitioning | OS concepts (synchronization, scheduling) apply at cluster scale |
| Security | Authentication, cryptography, exploits | OS enforces memory isolation, privilege levels |
FAQ
Q: What's the difference between a process and a thread?
A: A process is an independent program with its own memory space. Threads are lightweight execution units within a process that share the same memory. Multiple threads can run in parallel (multi-core) or concurrently (time-sharing) within one process.
Q: How does the OS prevent one process from reading another's memory?
A: Each process has its own page table. The CPU's Memory Management Unit (MMU) translates virtual addresses through the current process's page table. Any access outside the mapped virtual address space triggers a segfault. The kernel page table is mapped into every process but protected (not accessible from user mode).
Q: What's the difference between a page fault and a segfault?
A: A page fault is a normal OS event — a valid page isn't currently in RAM, so the OS loads it from disk and execution continues. A segfault (SIGSEGV) is a fatal access to an address the process has no right to access — the OS sends a signal that usually terminates the process.
Q: What happens on a context switch?
A: The OS saves the current process's registers, program counter, and flags into its PCB, then loads the next process's PCB into the CPU registers. If switching to a different process (not just different thread), the TLB is also flushed (or ASID-tagged entries invalidated).
Q: How does virtual memory enable isolation and security?
A: Each process sees its own virtual address space (commonly 0–2⁴⁸ bytes on x86-64). The kernel controls the page tables — it maps each process's pages to different physical frames. Process A's virtual address 0x1000 and Process B's virtual address 0x1000 point to completely different physical RAM locations.
Q: What is the difference between a semaphore and a mutex in practice?
A: A mutex should be unlocked by the same thread that locked it — it provides ownership semantics and is used for mutual exclusion. A semaphore is a signaling mechanism without ownership — it's ideal for producer-consumer (producer signals, consumer waits). Using a semaphore as a mutex is possible but signals/waits can come from any thread, which can lead to subtle bugs.