OS · 90 topics
What is an operating system, and what are its main functions?
An operating system (OS) is system software that manages hardware resources and provides services to applications, acting as the interface between users, programs and hardware.
Main functions: process management (creation, scheduling, termination), memory management (allocation, virtual memory, protection), file system management, device and I/O management, security and access control, and a user interface (shell or GUI) plus the system call interface.
Goals: convenience for users, efficient use of resources, and isolation so programs cannot damage each other or the system.
What is the difference between the kernel and the operating system? What are monolithic, microkernel and hybrid kernels?
The kernel is the core part of the OS that runs in privileged mode and controls the CPU, memory and devices; the OS also includes system libraries, utilities, the shell and other software.
Monolithic kernel (Linux): most services (scheduler, file systems, drivers, networking) run in kernel space as one large program; fast, but a faulty driver can crash the system.
Microkernel (Minix, QNX): only minimal functions (scheduling, memory, IPC) in the kernel, with other services as user-space servers; more modular and robust, but more message passing overhead.
Hybrid (Windows NT, macOS): a mix of both, keeping some services in the kernel for speed.
What are user mode and kernel mode, and how does the CPU switch between them?
Kernel mode (privileged) can execute any instruction and access all memory and hardware; user mode is restricted, so a buggy application cannot corrupt the system.
The CPU switches to kernel mode on a system call, an interrupt or an exception, and returns to user mode after the kernel finishes (a mode bit in a CPU register records the current mode).
Privileged instructions (I/O, changing page tables, halting) trigger a fault if executed in user mode.
What is a system call, and how does it work?
A system call is the controlled entry point through which a user program asks the kernel for a service, such as opening a file, creating a process or allocating memory.
Flow: the program calls a library wrapper (for example open or write in libc), which places the call number and arguments in registers and executes a trap instruction (syscall); the CPU switches to kernel mode and jumps to the kernel's handler; the kernel validates arguments, performs the work, and returns the result to user mode.
Categories: process control (fork, exec, exit), file management (open, read, write, close), device management (ioctl), information (getpid), and communication (pipe, socket). A library function such as printf may call write underneath; strace shows the actual system calls.
What is an interrupt, and how does it differ from an exception (trap)?
An interrupt is an asynchronous signal from hardware (a keyboard press, a disk finishing a read, a timer tick) that makes the CPU pause its current work and run an interrupt handler.
An exception or trap is synchronous and caused by the running instruction: a divide by zero, a page fault, or an intentional system call.
Handling: save the CPU state, look up the handler in the interrupt vector table, run it in kernel mode, then restore the state and resume (or schedule another process). The timer interrupt is how the OS regains control for preemptive scheduling.
Describe the boot process.
Power on: firmware (BIOS or UEFI) runs hardware checks (POST) and finds a boot device.
The bootloader (for example GRUB) loads the kernel image, and often an initial RAM disk, into memory and starts it.
The kernel initializes memory management, drivers and devices, mounts the root file system, and starts the first user-space process (init or systemd, PID 1), which launches the remaining services and login.
What is the difference between a program and a process? What does a process's memory layout look like?
A program is a passive file of instructions on disk; a process is a running instance with its own address space, registers, open files and execution state. One program can have many processes.
Typical layout from low to high addresses: text (code, read-only), data (initialized globals), BSS (uninitialized globals, zeroed), heap (dynamic allocation, grows upward), and stack (function calls and local variables, grows downward), with memory-mapped regions in between.
What are the states of a process, and what is a process control block (PCB)?
States: New (being created), Ready (waiting for the CPU), Running (executing), Waiting or Blocked (waiting for I/O or an event), and Terminated. Transitions: Ready to Running when the scheduler dispatches it, Running to Ready on preemption, Running to Waiting on an I/O request, Waiting to Ready when the event completes.
The PCB is the kernel's data structure for a process: process ID, state, program counter and CPU registers, scheduling information, memory management information (page tables), open file descriptors, accounting data and parent and child links. It is saved and restored during context switches.
How do fork() and exec() work?
fork() creates a child process that is a copy of the parent (copy-on-write makes this cheap); it returns 0 in the child, the child's PID in the parent, and -1 on failure.
exec() replaces the calling process's memory image with a new program; the PID stays the same and the call does not return on success.
The classic shell pattern is fork, then exec in the child to run a command, while the parent calls wait() to collect the exit status.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid < 0) { perror("fork"); exit(1); }
if (pid == 0) { // child
execlp("ls", "ls", "-l", NULL); // replaces the child's image
perror("exec failed");
_exit(1);
} else { // parent
int status;
waitpid(pid, &status, 0); // reap the child
printf("child exited with %d\n", WEXITSTATUS(status));
}
return 0;
}What are zombie and orphan processes, and how do you handle them?
Zombie: a child that has exited but whose entry remains in the process table because the parent has not yet called wait() to read its exit status; it uses no CPU or memory, only a table slot, and shows as Z (defunct) in ps. Fix by having the parent call wait or waitpid (or handle SIGCHLD); killing the zombie itself does nothing, you must fix or end the parent.
Orphan: a child whose parent has exited while it is still running; the init process (PID 1) adopts it and reaps it when it ends, so orphans are generally harmless.
What is a context switch, and why is it expensive?
A context switch saves the state of the running process or thread (registers, program counter, stack pointer) in its PCB and loads the saved state of another, so the CPU can multitask.
Costs: the saving and loading work itself, scheduler overhead, and indirect costs such as cache and TLB invalidation (especially when switching between processes with different address spaces), which make the next instructions slower.
Thread switches inside the same process are cheaper because the address space stays the same. Reduce context switching by limiting runnable threads and system call churn.
What is the difference between a process and a thread?
A process has its own address space, file descriptors and resources; a thread is a unit of execution inside a process, and all threads of a process share its code, heap, global data and open files, while each has its own stack, registers and program counter.
Creation and switching are cheaper for threads, and communication is easy through shared memory (but needs synchronization to avoid races); processes are better isolated, so a crash in one does not usually kill another.
Use processes for isolation and security, threads for fine-grained concurrency within one application.
What are user-level threads and kernel-level threads, and what are the multithreading models?
User-level threads are managed by a library without kernel knowledge: fast to create and switch, but if one blocks in a system call the whole process blocks, and they cannot use several cores.
Kernel-level threads are managed by the OS: they can run in parallel on several cores and block independently, at higher creation and switching cost.
Models: many-to-one (many user threads on one kernel thread), one-to-one (each user thread has a kernel thread, as in Linux and Windows), and many-to-many (multiplexed, as in some runtimes and green-thread systems such as Go's goroutines).
What do threads share, and what are the benefits and risks of multithreading?
Shared: code, global and heap data, open files and signal handlers. Private: stack, registers, thread ID and thread-local storage.
Benefits: responsiveness (keep a UI or server responsive during blocking work), resource sharing, lower overhead than processes, and use of multiple cores.
Risks: race conditions, deadlocks, harder debugging, and false sharing and cache contention; protect shared data with locks or use message passing.
What are the inter-process communication (IPC) mechanisms?
Pipes (unidirectional byte streams between related processes) and named pipes or FIFOs (between unrelated processes through a file name).
Message queues (structured messages through the kernel), shared memory (the fastest, since processes map the same memory but need synchronization), sockets (local or network communication), and signals (simple notifications).
Choose by need: shared memory for high throughput, pipes for simple streaming (command-line pipelines), sockets for network or client-server designs, message queues for decoupled messaging.
What are signals, and how do SIGTERM and SIGKILL differ?
A signal is a software notification delivered to a process (for example SIGINT from Ctrl+C, SIGSEGV on an invalid memory access, SIGCHLD when a child exits).
SIGTERM politely asks a process to terminate and can be caught so it can clean up; SIGKILL (signal 9) cannot be caught, blocked or ignored and ends the process immediately without cleanup, so use it as a last resort. SIGSTOP likewise cannot be caught.
Handlers should be short and only use async-signal-safe functions.
What is the difference between multiprogramming, multitasking, multiprocessing and multithreading?
Multiprogramming: keeping several programs in memory so the CPU switches to another when one waits for I/O, improving utilization.
Multitasking (time-sharing): rapidly switching among tasks with time slices so users see them as running at once.
Multiprocessing: using more than one CPU or core to run tasks truly in parallel.
Multithreading: running several threads within one process. Concurrency means making progress on several tasks (possibly by interleaving), while parallelism means executing them at the same instant on different cores.
What is a daemon process, and what is PID 1?
A daemon is a background process, usually started at boot and detached from a terminal, that provides a service (web server, scheduler, logging); names often end in d, such as sshd or crond.
PID 1 is the first user-space process (init or systemd), the ancestor of all others; it starts services, adopts orphans and reaps zombies. In containers, the process running as PID 1 must also handle signals and reap children, which is why lightweight init programs are sometimes added.
What does the CPU scheduler do, and which metrics evaluate scheduling algorithms?
The scheduler picks which ready process runs next on a CPU; the dispatcher then performs the context switch and gives it the CPU.
Metrics: CPU utilization (keep the CPU busy), throughput (processes completed per unit time), turnaround time (completion minus arrival), waiting time (time spent in the ready queue = turnaround minus burst time), and response time (arrival to first run).
Interactive systems care most about response time; batch systems about throughput and turnaround.
What is the difference between preemptive and non-preemptive scheduling?
Non-preemptive: once a process gets the CPU it keeps it until it finishes or blocks; simple and low overhead, but a long job can delay everyone (FCFS and non-preemptive SJF).
Preemptive: the OS can take the CPU away (for a time-slice expiry or a higher-priority process), which improves responsiveness and fairness but adds context-switch overhead and requires careful handling of shared data (round robin, SRTF, preemptive priority).
Modern general-purpose operating systems are preemptive; cooperative multitasking relies on processes yielding voluntarily and can be stalled by one that never does.
Explain FCFS scheduling and the convoy effect.
First-Come, First-Served runs processes in arrival order, non-preemptively; it is simple and fair in arrival order, but average waiting time can be long.
Convoy effect: short processes get stuck behind one long CPU-bound process, which lowers utilization of I/O devices and hurts response time.
Explain SJF and SRTF. What are their problems?
Shortest Job First picks the ready process with the smallest next CPU burst; it minimizes average waiting time (provably optimal for that metric) but is non-preemptive. Shortest Remaining Time First is its preemptive version: a newly arrived process with a shorter remaining time takes the CPU.
Problems: the next burst length is unknown and must be predicted (for example with exponential averaging of past bursts), and long processes can starve.
Explain round robin scheduling and how the time quantum affects it.
Each process runs for at most one time quantum, then goes to the back of the ready queue; it gives good response time and fairness and is the basis of time-sharing.
A very large quantum behaves like FCFS; a very small quantum causes excessive context switching and wastes CPU time. A common rule is to pick a quantum longer than most CPU bursts (around 80%) but short enough for responsiveness (often 10 to 100 ms).
Explain priority scheduling, starvation and aging.
Each process has a priority and the highest-priority ready process runs (preemptive or not); priorities can be set internally (by resource needs) or externally (by importance).
Starvation: low-priority processes may wait indefinitely if higher-priority ones keep arriving. Aging gradually raises the priority of waiting processes so they eventually run.
What are multilevel queue and multilevel feedback queue scheduling?
Multilevel queue: the ready queue is split into separate queues (system, interactive, batch), each with its own algorithm, and CPU time is divided among the queues; a process stays in its queue.
Multilevel feedback queue (MLFQ): processes move between queues based on behavior: new jobs start at high priority with a short quantum, those that use their whole quantum drop to lower queues, and I/O-bound or interactive processes stay high; aging moves long-waiting jobs up. It approximates SJF without knowing burst times and is the basis of many real schedulers.
Compute the average waiting time for P1 (arrival 0, burst 5), P2 (arrival 1, burst 3) and P3 (arrival 2, burst 1) under FCFS, SJF, SRTF and round robin.
FCFS: order P1 (0 to 5), P2 (5 to 8), P3 (8 to 9). Waiting times are 0, 4 and 6, so the average is 10/3, about 3.33. Average turnaround is (5 + 7 + 7)/3, about 6.33.
Non-preemptive SJF: P1 runs 0 to 5; then P3 (5 to 6) and P2 (6 to 9). Waiting times are P1 0, P3 3, P2 5, so the average is 8/3, about 2.67.
SRTF: P1 runs 0 to 1, P2 preempts it (1 to 2), P3 preempts P2 (2 to 3), then P2 finishes (3 to 5) and P1 finishes (5 to 9). Waiting times are P1 4, P2 1, P3 0, so the average is 5/3, about 1.67 (the best of the four).
Round robin with quantum 2 (new arrivals queue before the preempted process): completion times are P1 9, P2 8, P3 5, giving waiting times 4, 4 and 2, so the average is 10/3, about 3.33.
Method: waiting time = completion time - arrival time - burst time. Always state your tie-breaking assumptions.
How does Linux schedule processes?
Linux uses a preemptive, priority-aware fair scheduler for normal tasks. The Completely Fair Scheduler (CFS) tracked each task's virtual runtime and always ran the task with the least of it (kept in a red-black tree), weighted by nice values; newer kernels (6.6 and later) use EEVDF, a related fair scheduler that also considers latency.
Real-time tasks use separate policies (SCHED_FIFO and SCHED_RR) that take priority over normal tasks, and each core has its own run queue with load balancing across cores.
Nice values range from -20 (highest priority) to 19 (lowest).
What is a race condition, and what is the critical section problem?
A race condition occurs when the outcome depends on the unpredictable timing of concurrent accesses to shared data, for example two threads doing counter = counter + 1, which is a read-modify-write sequence that can lose updates.
The critical section is the code that accesses shared resources. A correct solution needs mutual exclusion (only one at a time), progress (a process outside the section cannot block others from entering), and bounded waiting (no process waits forever).
Solutions include locks (mutexes), semaphores, monitors, atomic hardware instructions (test-and-set, compare-and-swap), and Peterson's algorithm for two processes.
Show a race condition and fix it with a lock.
Python's global interpreter lock does not make counter += 1 atomic, because it compiles to separate load, add and store steps, so threads can still lose updates.
import threading
counter = 0
lock = threading.Lock()
def unsafe(n):
global counter
for _ in range(n):
counter += 1 # read-modify-write: updates can be lost
def safe(n):
global counter
for _ in range(n):
with lock: # only one thread in the critical section
counter += 1
threads = [threading.Thread(target=safe, args=(100_000,)) for _ in range(4)]
[t.start() for t in threads]
[t.join() for t in threads]
print(counter) # 400000 with the lockWhat is the difference between a mutex and a semaphore?
A mutex is a locking mechanism with ownership: only the thread that locked it can unlock it, and it protects a critical section (value 0 or 1).
A semaphore is a signaling mechanism with a counter, manipulated by wait (P, decrement and block if zero) and signal (V, increment and wake a waiter); a counting semaphore allows up to N concurrent users, while a binary semaphore behaves like a lock but without ownership, so any thread can signal it.
Use a mutex for mutual exclusion and a semaphore for resource counting and for signaling between threads (such as producer and consumer).
What are monitors and condition variables?
A monitor is a high-level construct that bundles shared data with the procedures that access it, guaranteeing that only one thread is active inside at a time (Java synchronized methods are an example).
Condition variables (wait, signal, broadcast) let a thread sleep inside a monitor or mutex until a condition becomes true; always wait in a loop that rechecks the condition, because of spurious wakeups and because another thread may have changed the state first.
When would you use a spinlock instead of a mutex?
A spinlock makes a thread busy-wait in a loop until the lock is free, wasting CPU but avoiding a context switch; it is appropriate for very short critical sections on multicore systems, and in kernels where sleeping is not allowed (such as interrupt handlers).
A mutex puts the waiting thread to sleep, which is better for longer critical sections or when the lock holder may block; on a single core, spinning is useless because the holder cannot run while you spin.
Solve the producer-consumer (bounded buffer) problem with semaphores.
Use three semaphores: empty (free slots, starts at N), full (filled slots, starts at 0) and mutex (protects the buffer, starts at 1).
The order of waits matters: acquiring the mutex before empty or full can deadlock, because a producer could hold the mutex while waiting for space that only a consumer (blocked on the mutex) can free.
semaphore mutex = 1, empty = N, full = 0;
void producer() {
while (1) {
item = produce();
wait(empty); // wait for a free slot
wait(mutex); // enter critical section
insert(item);
signal(mutex);
signal(full); // one more filled slot
}
}
void consumer() {
while (1) {
wait(full); // wait for an item
wait(mutex);
item = remove();
signal(mutex);
signal(empty); // one more free slot
consume(item);
}
}Solve the readers-writers problem.
Many readers may read at once, but a writer needs exclusive access. A simple semaphore solution lets the first reader lock out writers and the last reader let them back in.
This version favors readers, so writers can starve; a writer-preference or fair (queue-based) version prevents that at some cost in concurrency.
semaphore rw_mutex = 1, mutex = 1;
int read_count = 0;
void writer() {
wait(rw_mutex);
write();
signal(rw_mutex);
}
void reader() {
wait(mutex);
if (++read_count == 1) wait(rw_mutex); // first reader blocks writers
signal(mutex);
read();
wait(mutex);
if (--read_count == 0) signal(rw_mutex); // last reader releases writers
signal(mutex);
}What is the dining philosophers problem, and how do you avoid deadlock in it?
Five philosophers sit around a table with one fork between each pair and need both adjacent forks to eat; if everyone picks up their left fork at once, they deadlock.
Solutions: allow at most four philosophers to sit at once, impose an ordering on resources (pick up the lower-numbered fork first), make one philosopher pick up forks in the opposite order (asymmetric), or pick up both forks atomically inside a monitor.
It illustrates deadlock, starvation and the need for resource ordering.
What is priority inversion, and how is it solved?
A high-priority task waits for a lock held by a low-priority task, while a medium-priority task preempts the low-priority one, so the high-priority task is effectively delayed by the medium one (this famously affected the Mars Pathfinder).
Solutions: priority inheritance (the lock holder temporarily inherits the waiter's priority), priority ceiling protocols, or avoiding locks shared between very different priorities.
What is a deadlock, and what are the four necessary conditions?
A deadlock is a state where a set of processes is permanently blocked, each waiting for a resource held by another in the set.
Coffman's four conditions must all hold: mutual exclusion (a resource is held exclusively), hold and wait (a process holds resources while waiting for more), no preemption (resources cannot be forcibly taken away), and circular wait (a cycle of processes each waiting for the next one's resource).
Breaking any one condition prevents deadlock.
How do you prevent deadlocks? Show a lock-ordering fix.
Break one condition: avoid mutual exclusion where possible (read-only or sharable resources), require processes to request all resources at once (no hold and wait, at the cost of utilization), allow preemption (release and retry), or impose a global ordering on resources (no circular wait), which is the most practical.
Other practical tools: lock timeouts or try-lock with backoff, and holding locks for as short a time as possible.
# Deadlock-prone: thread 1 locks A then B, thread 2 locks B then A.
# Fix: always acquire locks in one global order.
def transfer(src, dst, amount):
first, second = sorted((src, dst), key=lambda acct: acct.id)
with first.lock:
with second.lock:
src.balance -= amount
dst.balance += amountWhat is deadlock avoidance, and how does the Banker's algorithm work?
Avoidance grants a request only if the system remains in a safe state: a state in which some order of running all processes to completion exists (a safe sequence).
Banker's algorithm keeps Available (free resources), Max (the most each process may need), Allocation (current holdings) and Need = Max - Allocation. Safety check: set Work = Available; repeatedly find an unfinished process whose Need is at most Work, pretend it finishes and add its Allocation to Work; if all processes can finish, the state is safe.
For a request, check that it is within Need and Available, tentatively grant it, run the safety check, and roll back if the state would be unsafe. It requires knowing maximum needs in advance, so it is rarely used in general-purpose systems.
How are deadlocks detected and recovered from?
Detection: build a resource allocation graph or a wait-for graph and look for cycles (with single-instance resources a cycle means deadlock; with multiple instances, use a detection algorithm similar to Banker's).
Recovery: terminate one or all deadlocked processes, or preempt resources and roll back a process to a checkpoint, choosing victims by priority, progress and cost; avoid always choosing the same victim, which causes starvation.
Many general-purpose systems simply ignore the problem (the ostrich approach) and rely on developers; databases detect deadlocks and abort one transaction.
What is the difference between deadlock, livelock and starvation?
Deadlock: processes are blocked forever waiting for each other.
Livelock: processes keep changing state in response to each other (for example repeatedly backing off and retrying) but make no progress, like two people stepping aside in a corridor.
Starvation: a process waits indefinitely because others are always favored (an unfair scheduler or lock), even though the system as a whole keeps working; aging and fair queues fix it.
What happens if a thread locks a non-recursive mutex twice?
It deadlocks itself: the second lock call blocks waiting for a mutex that only the same blocked thread could release.
A recursive (reentrant) mutex tracks the owner and a count, allowing the same thread to lock it repeatedly and requiring the same number of unlocks.
Prefer restructuring code so locks are not needed recursively, because reentrant locks can hide design problems.
What is the difference between logical (virtual) and physical addresses?
A logical (virtual) address is what a program generates and sees; a physical address is the actual location in RAM.
The memory management unit (MMU) translates logical to physical addresses at run time using page tables (or base and limit registers in simple schemes), which lets each process have its own private address space, lets the OS place data anywhere in RAM, and protects processes from each other.
How does contiguous memory allocation work, and what are first fit, best fit and worst fit?
Each process gets one contiguous block of memory from a list of free holes.
First fit takes the first hole that is large enough (fast, usually good); best fit takes the smallest sufficient hole (leaves small unusable fragments); worst fit takes the largest hole (leaves a large remainder, but performs poorly in practice).
It suffers from external fragmentation; compaction (moving processes to merge free space) can fix it but is expensive.
What are internal and external fragmentation, and how are they solved?
Internal fragmentation: wasted space inside an allocated block (for example a 4 KB page allocated for 3 KB of data, wasting 1 KB, or fixed-size partitions).
External fragmentation: enough total free memory exists but it is split into small non-contiguous holes (variable-size partitions and segmentation).
Paging removes external fragmentation but causes some internal fragmentation (the last page of a process); segmentation has the opposite trade-off. Compaction, paging and good allocators reduce the problem.
How does paging work?
Physical memory is divided into fixed-size frames and the logical address space into pages of the same size (commonly 4 KB); the page table maps each page number to a frame number.
A logical address is split into a page number (used to index the page table) and an offset (the position within the page); the physical address is the frame number followed by the same offset.
Benefits: no external fragmentation, easy sharing and protection (permission bits per page), and the basis of virtual memory; costs: page table memory and an extra memory access per translation (reduced by the TLB).
For a 32-bit address space with 4 KB pages, how many bits are the page number and offset, and how large is the page table?
4 KB = 2^12 bytes, so the offset is 12 bits and the page number is 32 - 12 = 20 bits, giving 2^20 (about 1 million) pages.
With 4-byte page table entries, a flat page table takes 2^20 x 4 bytes = 4 MB per process, which is wasteful when most of the address space is unused.
Fix: use a multilevel page table (next question), where only the used parts of the table exist.
What are multilevel, hashed and inverted page tables?
Multilevel (hierarchical): the page table is itself paged. A 32-bit address with 4 KB pages can use 10 bits for the outer table, 10 bits for the inner table and 12 bits of offset, so each table has 1,024 entries of 4 bytes (4 KB, exactly one page) and unused regions need no inner tables. x86-64 uses four levels (five with the extension) for 48-bit addresses.
Hashed page table: the page number is hashed to find entries, useful for sparse large address spaces.
Inverted page table: one entry per physical frame (not per virtual page), saving space but making lookups slower (usually with a hash), and harder to share pages.
What is the TLB, and how do you compute effective access time?
The translation lookaside buffer is a small, fast hardware cache of recent page-to-frame translations; on a hit the translation costs almost nothing, while on a miss the CPU walks the page table in memory. Context switches between processes may flush it unless entries are tagged with address-space IDs.
Effective access time (EAT) = hit ratio x (TLB time + memory time) + miss ratio x (TLB time + page-table access + memory time).
Example with a single-level page table, TLB lookup 20 ns, memory access 100 ns: at 80% hit ratio EAT = 0.8 x 120 + 0.2 x 220 = 140 ns; at 98% hit ratio EAT = 0.98 x 120 + 0.02 x 220 = 122 ns.
What is the difference between paging and segmentation?
Paging uses fixed-size pages, is invisible to the programmer, and avoids external fragmentation; segmentation divides memory into variable-size logical units (code, data, stack, modules), matches how programmers think, and makes protection and sharing by unit natural, but causes external fragmentation.
Address format: page number and offset versus segment number and offset (checked against a segment limit).
Many systems combine them (segmented paging); modern 64-bit Linux mostly relies on paging.
What is virtual memory, and what are its benefits?
Virtual memory lets a process use an address space larger than physical RAM by keeping only the needed pages in memory and the rest on disk (swap or the backing file); the OS and MMU make it transparent.
Benefits: programs larger than RAM can run, more processes fit in memory at once, each process is isolated with its own address space, memory can be shared, and loading is faster because only needed pages are read.
Cost: page faults are slow, so performance depends on locality of reference.
What is demand paging, and what happens on a page fault?
Demand paging loads a page into memory only when it is first accessed.
Page fault sequence: the CPU raises a fault when the page table marks the page invalid; the OS checks that the address is legal (otherwise it sends a segmentation fault); finds a free frame (or evicts a victim page, writing it back if dirty); reads the page from disk; updates the page table and TLB; and restarts the faulting instruction.
A minor fault finds the page already in memory and just maps it (for example a shared library or first-touch zero page); a major fault needs disk I/O.
How do page faults affect effective access time?
EAT = (1 - p) x memory access time + p x page fault service time, where p is the page fault rate.
Example: memory access 200 ns, fault service time 8 ms (8,000,000 ns), p = 1 in 1,000: EAT = 0.999 x 200 + 0.001 x 8,000,000, about 8,200 ns, a slowdown of about 41 times. To keep slowdown under 10%, p must be below about 1 in 400,000.
This is why keeping the fault rate extremely low matters.
Explain the page replacement algorithms FIFO, Optimal, LRU and Clock, with the classic example.
FIFO evicts the oldest page (simple, can evict a heavily used page, and suffers Belady's anomaly). Optimal (Belady's algorithm) evicts the page that will not be used for the longest time (the lowest possible faults, but needs knowledge of the future, so it is used as a benchmark). LRU evicts the least recently used page (a good approximation of Optimal based on locality; exact LRU needs hardware support or counters or a stack). Clock (second chance) approximates LRU with a reference bit and a circular pointer.
Reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1 with 3 frames: FIFO gives 15 page faults, LRU gives 12, and Optimal gives 9.
Dirty pages need to be written back on eviction, so replacement policies often prefer clean pages.
What is Belady's anomaly?
With some algorithms (notably FIFO), giving a process more frames can increase the number of page faults.
Example: reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 under FIFO gives 9 faults with 3 frames but 10 faults with 4 frames.
Stack algorithms such as LRU and Optimal never show the anomaly, because the set of pages held with n frames is always a subset of those held with n + 1 frames.
How would you implement an LRU cache or LRU page replacement?
Exact LRU needs to track recency on every access: with a hash map plus a doubly linked list (or an ordered dictionary) both get and put are O(1). In hardware, systems use approximations such as reference bits with the clock algorithm because exact tracking on every memory access is too costly.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key) # mark as most recently used
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict least recently usedWhat is thrashing, what causes it, and how do you fix it?
Thrashing is when the system spends more time paging than executing, because processes do not have enough frames for their active pages, so nearly every access faults.
Vicious cycle: low CPU utilization leads the OS to admit more processes, which causes more faults and even lower utilization.
Fixes: reduce the degree of multiprogramming (suspend or swap out processes), use the working-set model or page-fault-frequency control to give each process enough frames, add RAM, improve locality, and use local replacement so one process cannot steal frames from others.
What is the working set model?
The working set of a process is the set of pages it referenced in its most recent window of time (or references); if the sum of all working sets exceeds available memory, thrashing occurs.
The OS tries to keep each process's working set resident, and suspends processes when memory is overcommitted.
What is copy-on-write (COW)?
After fork(), parent and child initially share the same physical pages, marked read-only; when either one writes, a page fault occurs and the OS copies just that page for the writer.
It makes fork() fast and saves memory, especially when the child immediately calls exec(), and is also used for snapshots and shared zero pages.
What are memory-mapped files (mmap), and why are they useful?
mmap maps a file (or anonymous memory) into a process's address space, so reads and writes become ordinary memory accesses; the OS loads pages on demand through the page cache and writes dirty pages back.
Benefits: no explicit read and write calls, less copying, shared memory between processes mapping the same file, and fast access to large files such as datasets or model weights.
What is the difference between stack and heap memory?
Stack: stores function call frames and local variables, allocated and freed automatically in last-in-first-out order, very fast, but limited in size (stack overflow from deep recursion or large locals).
Heap: dynamically allocated memory (malloc, new) that lives until freed or garbage collected, flexible in size and lifetime, but slower and subject to fragmentation, leaks and dangling pointers.
Each thread has its own stack, while all threads share the heap.
How does malloc work, and what is a memory leak?
malloc manages free lists on the heap: small requests are served from memory obtained with brk or sbrk, while large requests (above a threshold such as 128 KB in glibc) use mmap directly; free returns blocks to the allocator, which may coalesce neighbors, and the memory is not always returned to the OS.
A memory leak is allocated memory that is no longer reachable or needed but never freed, so usage grows over time; find leaks with tools such as Valgrind, AddressSanitizer and heap profilers, and in managed languages look for objects held by caches or global references.
How does memory protection work, and what is the difference between a page fault and a segmentation fault?
Protection uses base and limit registers in simple systems and per-page permission bits (read, write, execute, user or supervisor) in paging systems; hardware raises a fault on a violation, and features such as the no-execute (NX) bit stop data pages from running as code.
A page fault is a normal event when a valid page is not currently mapped (the OS can handle it); a segmentation fault is what a process receives (SIGSEGV) when it accesses an invalid address or violates permissions, and by default it terminates the process.
What are swapping and huge pages?
Swapping moves entire processes or (in modern systems) individual pages between RAM and disk to free memory; swap space is a disk area reserved for this. Heavy swapping slows the system sharply.
Huge pages (2 MB or 1 GB instead of 4 KB) cut the number of page table entries and TLB misses for large memory workloads (databases, large models), at the cost of more internal fragmentation and less flexible allocation.
Why does locality of reference matter?
Temporal locality (recently used data is used again) and spatial locality (nearby data is used soon) are why caches, TLBs and paging work.
Writing code that follows memory layout matters: traversing a 2D array row by row (row-major order in C) is much faster than column by column because it uses each cache line fully.
// Fast: sequential access, good spatial locality
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
sum += a[i][j];
// Slow: strided access, frequent cache and TLB misses
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
sum += a[i][j];How are frames allocated to processes, and what are global and local replacement?
Allocation policies: equal (the same number of frames per process) or proportional (according to process size or priority), always with a minimum number of frames needed to run an instruction.
Global replacement lets a process evict a frame belonging to any process (better utilization, but one process can hurt another's fault rate); local replacement picks a victim only among the process's own frames (more predictable, but may waste memory).
What is a file system, and how is data organized on disk?
A file system organizes how files and directories are stored, named, located and protected on a storage device, and provides operations such as create, open, read, write, seek, delete and set permissions.
Typical layout: a boot block, a superblock (file system metadata: size, block size, free counts), free-space management structures, an inode table (file metadata), and data blocks; directories map names to inodes.
Common file systems: ext4, XFS and Btrfs (Linux), NTFS (Windows), APFS (macOS), FAT32 and exFAT (removable media).
What is an inode, and what does it store?
An inode is the on-disk structure holding a file's metadata: type, size, owner and group, permissions, timestamps, link count and pointers to its data blocks; it does not store the file name, which lives in directory entries that map names to inode numbers.
Inode pointers are usually direct blocks plus single, double and triple indirect blocks, so small files are fast and large files are supported.
A file system can run out of inodes (check with df -i) even when space remains, for example with millions of tiny files.
What is the difference between a hard link and a soft (symbolic) link?
A hard link is another directory entry pointing to the same inode: it is indistinguishable from the original, the data persists until all links are removed (the link count reaches zero), and it cannot cross file systems or (normally) link directories.
A soft link is a separate small file containing a path to the target; it can cross file systems and point to directories, but it breaks (dangles) if the target is removed or moved.
ln original.txt hard.txt # hard link (same inode)
ln -s original.txt soft.txt # symbolic link (stores a path)
ls -li original.txt hard.txt # show inode numbersWhat are the file allocation methods?
Contiguous: each file occupies consecutive blocks; fast sequential and direct access, but external fragmentation and difficulty growing files.
Linked: each block points to the next (FAT keeps the links in a table); no external fragmentation, but slow random access and fragile if a pointer is lost.
Indexed: an index block (or inode) lists all data block addresses; supports direct access and no external fragmentation, with overhead for the index (Unix inodes use multilevel indexing).
What is journaling, and why do file systems use it?
A journal (write-ahead log) records intended metadata changes (and optionally data) before applying them; after a crash the file system replays or discards the journal instead of scanning the whole disk, so recovery is fast and the file system stays consistent.
Examples: ext3 and ext4, NTFS and XFS; copy-on-write file systems (Btrfs, ZFS, APFS) achieve consistency differently by never overwriting live data in place.
Journaling protects consistency of the file system structure; it does not replace backups.
How is free space managed on a disk?
Bit vector (bitmap): one bit per block, simple and fast to find contiguous free space, but needs memory for large disks.
Linked list of free blocks, grouping or counting (store runs of free blocks), and extent- or tree-based structures in modern file systems.
What is a file descriptor? What are stdin, stdout and stderr?
A file descriptor is a small non-negative integer the kernel gives a process to refer to an open file, socket, pipe or device; the per-process table points to system-wide open file entries.
By convention 0 is standard input, 1 is standard output and 2 is standard error; redirection (>, 2>&1, <) and pipes (|) work by rewiring these descriptors.
Each process has a limit on open descriptors (ulimit -n); the error "too many open files" usually means a leak (sockets or files not closed) or a low limit.
What is the page cache, and why does Linux show little free memory?
Linux uses spare RAM to cache file data (the page cache) and metadata, so repeated reads avoid the disk, and this memory is released when applications need it.
Look at the available column of free -h rather than free; high usage that is mostly cache is healthy, while low available memory plus heavy swap activity signals real pressure.
Writes go to the cache first and are flushed to disk later (dirty pages), which is why sync and fsync exist for durability.
What are the disk scheduling algorithms?
FCFS: serve requests in arrival order (fair, long head movement). SSTF: serve the request closest to the head (low seek time, but can starve distant requests).
SCAN (elevator): the head sweeps in one direction serving requests, then reverses; C-SCAN sweeps one way and returns to the start without serving, for more uniform waiting; LOOK and C-LOOK turn around at the last request instead of the disk end.
These matter for spinning disks with seek time; SSDs have no mechanical seek, so modern kernels use simple schedulers (such as none or mq-deadline) for them.
What are the common RAID levels?
RAID 0: striping across disks for speed, no redundancy (one failure loses everything). RAID 1: mirroring, full redundancy, half the usable capacity.
RAID 5: striping with distributed single parity (survives one disk failure, at least three disks, slower writes). RAID 6: double parity (survives two failures, at least four disks).
RAID 10: striped mirrors, good speed and redundancy at higher cost. RAID is not a backup: it does not protect against deletion or corruption.
What is the difference between polling, interrupt-driven I/O and DMA?
Polling: the CPU repeatedly checks a device's status; simple, but wastes CPU time.
Interrupt-driven I/O: the device signals the CPU when it is ready, so the CPU can do other work; there is still per-byte CPU involvement for data transfer.
DMA (direct memory access): a DMA controller moves data between a device and memory without the CPU, which is only interrupted when the whole transfer completes; best for large transfers such as disks and network cards.
What is the difference between blocking, non-blocking and asynchronous I/O, and how do select, poll and epoll work?
Blocking: the call waits until the operation completes. Non-blocking: it returns immediately (often with a would-block error) if the operation cannot complete. Asynchronous: the operation is started and completion is notified later (callbacks, signals, io_uring on Linux).
select and poll watch many file descriptors but scan the whole list on every call (linear in the number of descriptors); epoll (Linux) registers descriptors once and returns only the ready ones, which scales to tens of thousands of connections, and is the basis of event loops in nginx, Node.js and Python's asyncio.
A thread-per-connection server wastes memory and context switches at high connection counts; an event loop with non-blocking I/O handles many connections on a few threads.
What is zero-copy I/O?
Normally sending a file over a socket copies data from disk to the kernel page cache, to a user buffer, back to a kernel socket buffer, then to the network card.
Zero-copy calls such as sendfile (and mmap) let the kernel move data directly between buffers (or use DMA), skipping user-space copies, which saves CPU and memory bandwidth for static file servers and data pipelines.
Which Linux commands do you use to inspect processes, memory, disk and ports?
ps aux | grep python # list processes
top / htop # live CPU and memory per process
free -h # memory (read the 'available' column)
vmstat 1 # CPU, memory, swap, I/O every second
iostat -x 1 # disk utilization and latency
df -h ; du -sh * # disk space by file system / directory
lsof -i :8080 # which process uses a port
ss -ltnp # listening sockets and their processes
strace -p <pid> # trace system calls of a process
kill -15 <pid> ; kill -9 <pid> # SIGTERM first, SIGKILL as last resort
nice -n 10 cmd ; renice 5 -p <pid> # change scheduling priority
dmesg | tail # kernel messages (OOM kills, hardware errors)How do Linux file permissions work?
Each file has an owner, a group and permissions for owner, group and others, each made of read (4), write (2) and execute (1) bits; chmod 755 means owner rwx, group r-x, others r-x. Directories need execute permission to enter them.
chown changes owner and group; umask sets default permissions for new files; special bits include setuid and setgid (run with the file owner's or group's identity) and the sticky bit (only owners can delete files in a shared directory such as /tmp).
Use the least privilege necessary, and avoid running services as root.
ls -l script.sh # -rwxr-xr-x 1 user group ...
chmod 755 script.sh
chmod u+x script.sh
chown user:group file.txtWhat is load average, and how do you debug a slow server?
Load average (shown by uptime and top) is the average number of tasks that are running, runnable, or in uninterruptible sleep (usually waiting on disk) over 1, 5 and 15 minutes; compare it with the number of CPU cores (a load of 8 on 4 cores means tasks are queuing).
Method: check CPU (top: user, system and iowait percentages), memory (free -h, swap in and out in vmstat), disk (iostat, df), network (ss, sar) and the busiest processes; use strace or perf to see what a hot process is doing, and check logs and dmesg for errors.
High load with low CPU use usually means processes are blocked on I/O; high system time suggests heavy system calls or context switching.
What is the OOM killer, and how do you investigate an out-of-memory kill?
When Linux cannot find free memory (RAM and swap exhausted), the out-of-memory killer picks a process (by a badness score, oom_score) and kills it with SIGKILL to keep the system alive; Linux overcommits memory by default, so allocations can succeed even when the memory is not really available until it is touched.
Investigate with dmesg or journalctl ("Out of memory: Killed process ..."), monitor memory growth, and check limits: in containers, a cgroup memory limit triggers an OOM kill of the container's process (often exit code 137, which is 128 plus signal 9).
Fix by reducing memory use, raising limits, adding swap carefully, or fixing the leak.
What is the difference between virtual machines and containers?
A virtual machine runs a full guest OS (its own kernel) on virtual hardware provided by a hypervisor: strong isolation but heavier (gigabytes, slower startup). Type 1 hypervisors (KVM, Xen, ESXi) run directly on hardware; Type 2 (VirtualBox, VMware Workstation) run on a host OS.
A container is an isolated group of processes sharing the host kernel: lightweight (megabytes, near-instant startup) but with weaker isolation, and it can only run applications compatible with the host kernel.
Docker packages applications and their dependencies into images, runs them as containers, and pulls and pushes images through registries such as Docker Hub.
How do namespaces and cgroups make containers work?
Namespaces give a process its own isolated view of system resources: PID (process IDs), network (interfaces and ports), mount (file systems), UTS (hostname), IPC and user (ID mapping).
Control groups (cgroups) limit and account for resource usage per group of processes: CPU, memory, I/O and process counts; exceeding the memory limit triggers an OOM kill.
A union or overlay file system provides layered images; together these Linux kernel features, not a separate OS, are what a container is.
What are the main OS security mechanisms?
Authentication (who you are: passwords, keys, multi-factor) and authorization (what you may do: permissions, ACLs, roles), least privilege, and process isolation through address spaces and user and kernel modes.
Hardening features: address space layout randomization (ASLR), no-execute memory (NX), stack canaries, sandboxing (seccomp, namespaces, mandatory access control such as SELinux and AppArmor), and auditing and logging.
Common threats: buffer overflows, privilege escalation, malware and misconfigured permissions.
Why does multiprocessing speed up CPU-bound Python while threading often does not?
CPython's global interpreter lock lets only one thread run Python bytecode at a time, so threads cannot use several cores for CPU-bound Python code, though they work well for I/O-bound work because the lock is released while waiting on I/O.
Processes have separate interpreters and address spaces, so they run in parallel on different cores, at the cost of memory duplication and inter-process communication (pickling, shared memory).
asyncio uses a single-threaded event loop (built on epoll) for many concurrent I/O tasks, such as LLM API calls.
from concurrent.futures import ProcessPoolExecutor
def cpu_heavy(x):
return sum(i * i for i in range(x))
if __name__ == "__main__":
with ProcessPoolExecutor() as ex: # one worker process per core by default
results = list(ex.map(cpu_heavy, [10_000_000] * 8))How do memory mapping and the page cache affect loading large ML models and datasets?
Model files in memory-mappable formats (such as safetensors) can be mapped into the address space: pages load lazily on first access through the page cache, avoid an extra copy, and are shared between processes using the same file, so loading and starting many workers is faster and uses less RAM.
The first load reads from disk (cold cache) and later loads are fast (warm cache); this explains why a second run often starts much faster.
If the file does not fit in RAM, you get constant page faults and thrashing, so check available memory, and for big datasets prefer streaming or memory-mapped arrays.
How do OS concepts show up when training or serving ML models?
Processes and threads: data loader workers are separate processes (PyTorch's DataLoader with num_workers), and pinned (page-locked) host memory allows faster asynchronous copies to the GPU.
Memory: out-of-memory errors can be on the GPU or on the host (OOM killer), and swapping or page cache pressure slows data loading; use available-memory metrics for both.
Containers: GPU containers share the host kernel and driver, with cgroup limits on CPU and memory, so a memory limit set too low kills the training job.
Scheduling and locality: CPU affinity and NUMA placement matter for high-throughput inference servers, and too many threads per core cause context-switch overhead.
How should a model-serving process handle shutdown signals?
Orchestrators such as Kubernetes send SIGTERM and wait a grace period before SIGKILL, so the service should catch SIGTERM, stop accepting new requests, finish in-flight work, flush logs and close connections, then exit.
In containers the main process is PID 1, which does not get default signal handlers, so the application must handle SIGTERM explicitly (or run under a small init process) and should reap child processes.
import signal, sys
shutting_down = False
def handle_sigterm(signum, frame):
global shutting_down
shutting_down = True # stop accepting new work; let the loop drain and exit
signal.signal(signal.SIGTERM, handle_sigterm)