Operating System Interview Questions
Operating Systems is a core CS-fundamentals topic in software and SDE interviews. These are the questions interviewers actually ask, grouped by theme and tagged by experience level, with concise answers you can speak confidently.
170 questions with concise, interview-ready answers.
Contents
Operating System Basics
1. What is an operating system? Fresher
An operating system is the software layer that manages a computer's hardware and resources and provides services to application programs. It handles processes, memory, file systems, and I/O devices, and acts as an intermediary between the user and the hardware. Common examples are Windows, Linux, macOS, and Android.
2. What are the main functions of an operating system? Fresher
Process management (creating, scheduling and terminating processes), memory management (allocating and protecting address spaces), file system management (naming, storing and permissioning data), device and I/O management (drivers, buffering, spooling), and protection and security (isolating users and processes). Underlying all of them is resource arbitration: deciding who gets the CPU, memory or disk next, and enforcing that decision.
3. Why is an operating system called a resource manager? Fresher
Because every scarce resource — CPU time, physical memory, disk bandwidth, network sockets — has more claimants than capacity, and the OS decides the allocation and enforces it. It multiplexes each resource in time (the CPU via scheduling) or in space (memory via paging). Without that arbitration a single program could monopolise the machine or corrupt another's data.
4. What is the difference between multiprogramming and multitasking? Fresher
Multiprogramming keeps multiple programs in memory and switches the CPU to another whenever the running one waits for I/O, maximizing CPU utilization. Multitasking is an extension that rapidly time-shares the CPU among processes using small time slices so they appear to run simultaneously, giving better interactivity and response time. Multitasking is essentially multiprogramming with preemptive time-sharing.
5. What is the difference between multitasking and multiprocessing? Fresher
Multitasking is about how many tasks share one CPU, achieved by time-slicing so tasks appear concurrent. Multiprocessing is about how many physical CPUs or cores the system has, so tasks can genuinely run in parallel. A single-core machine can multitask but not multiprocess, and a multiprocessor system still needs multitasking because there are always more runnable threads than cores.
6. What is the difference between symmetric and asymmetric multiprocessing? 2–5 yrs
In symmetric multiprocessing every processor runs the same copy of the OS, shares memory, and can execute any task, with the scheduler balancing work across cores — this is what mainstream servers and phones use. In asymmetric multiprocessing one master processor runs the OS and assigns work to subordinate processors, which simplifies synchronisation but makes the master a bottleneck and a single point of failure.
7. What is a real-time operating system? Fresher
A real-time OS guarantees that a task completes within a bounded deadline, so correctness depends on timing as well as on the result. A hard real-time system treats a missed deadline as a failure — anti-lock brakes, pacemakers — while a soft real-time system merely degrades quality, as with video playback. Achieving this means predictable, preemptible kernels with bounded interrupt latency, usually at the cost of average throughput.
8. What is a batch operating system? Fresher
A batch OS groups jobs with similar requirements into batches and runs them without user interaction, with an operator or job scheduler feeding them in sequence. It was designed to keep expensive hardware busy when interactive terminals did not exist. Its weakness is response time — a short job queued behind a long one waits — which is the same convoy problem FCFS scheduling has today.
9. What is the difference between a time-sharing and a distributed operating system? 2–5 yrs
A time-sharing OS gives many users interactive access to one machine by rapidly switching the CPU between their processes. A distributed OS manages a collection of independent machines and presents them as a single system, handling remote resource access, distributed file systems and coordination across nodes. Time-sharing multiplexes one machine; a distributed OS aggregates many.
10. What is a bootloader and what happens during boot? 2–5 yrs
On power-up the firmware (BIOS or UEFI) runs a power-on self test and loads a small bootloader from a known location on disk. The bootloader locates the kernel image, loads it into memory, passes it parameters, and jumps to its entry point. The kernel then initialises hardware and memory management, mounts the root file system, and starts the first user-space process, which spawns everything else.
11. What is spooling? 2–5 yrs
Spooling (Simultaneous Peripheral Operation On-Line) buffers output for a slow device on disk so the producing process does not have to wait for the device. Print queues are the canonical example: the application writes the job to a spool directory and continues, while a daemon feeds the printer at its own pace. It decouples fast producers from slow devices and lets several jobs queue safely for one device.
12. What is the difference between a program and a process? 2–5 yrs
A program is a passive entity: an executable file sitting on disk with instructions and initial data. A process is that program in execution — an active entity with an address space, a program counter, registers, open file descriptors and a state in the scheduler. One program can back many processes, each with independent state, which is why running two copies of an editor does not make them share their documents.
Kernel, System Calls and OS Structure
13. What is the difference between kernel mode and user mode? Fresher
The CPU runs in two privilege levels: kernel (supervisor) mode, where code has full access to hardware and privileged instructions, and user mode, where application code runs with restricted access. User programs cannot directly touch hardware or critical resources; they request such services through system calls, which switch the CPU into kernel mode. This separation protects the OS and other processes from buggy or malicious user code.
14. What is the kernel? Fresher
The kernel is the core of the OS: the part that is always resident in memory and runs in privileged mode. It owns process scheduling, memory management, the file system layer, device drivers and the system call interface. Everything else — shells, utilities, window servers — is ordinary user-space software that reaches the hardware only by asking the kernel.
15. What is a system call? Fresher
A system call is the controlled entry point through which a user program requests a service from the kernel — open, read, write, fork, mmap. The call sets up arguments and executes a special trap instruction that switches the CPU into kernel mode at a fixed handler address, so user code can never jump into arbitrary kernel code. On return the mode switches back and the result is passed to the caller.
16. What are the main categories of system calls? 2–5 yrs
Process control (fork, exec, exit, wait), file management (open, read, write, close), device management (ioctl, read and write on device files), information maintenance (getpid, time, sysinfo) and communication (pipe, socket, shmget). Interviewers usually want the categories plus one real example each, not an exhaustive list.
17. Why is a system call more expensive than a normal function call? 2–5 yrs
A function call is a jump and a stack push. A system call has to trap into the kernel, switch the privilege level and the stack, save and restore registers, validate every argument coming from untrusted user memory, and on modern CPUs it may also flush speculative-execution mitigations. That is hundreds of cycles rather than a handful, which is why libraries buffer I/O — one write of 4 KB beats 4096 writes of one byte.
18. What is the difference between a monolithic kernel and a microkernel? 2–5 yrs
A monolithic kernel runs all core services — scheduler, memory manager, file systems, drivers — in a single privileged address space, so calls between them are fast function calls. A microkernel keeps only the bare minimum in kernel mode (address spaces, threads, IPC) and pushes drivers and file systems into user-space servers reached by message passing. Monolithic wins on performance; microkernel wins on isolation, because a crashing driver kills a server rather than the machine.
19. What is a hybrid kernel? 2–5 yrs
A hybrid kernel keeps the monolithic structure — most services in one privileged address space for speed — while borrowing microkernel ideas such as modularity, message passing between subsystems, and running some services in user space. Windows NT and XNU on macOS are usually described this way. The label is contested precisely because the practical design is a performance compromise rather than a clean architecture.
20. What is a loadable kernel module? 2–5 yrs
A loadable kernel module is code — typically a device driver or a file system — that can be inserted into or removed from a running kernel without rebooting. It gives a monolithic kernel much of a microkernel's flexibility while keeping the performance of in-kernel calls. The trade-off is unchanged: a module runs with full privilege, so a bug in one can panic the whole system.
21. What is an interrupt, and how does the OS handle it? Fresher
An interrupt is a signal from hardware that an event needs attention — a key press, a completed disk transfer, a timer tick. The CPU finishes the current instruction, saves minimal state, looks up the handler address in the interrupt vector table, and runs the interrupt service routine in kernel mode before restoring state. Interrupts are what let the OS overlap I/O with computation instead of polling devices.
22. What is the difference between an interrupt, a trap, and a fault? 2–5 yrs
An interrupt is asynchronous and comes from hardware external to the running instruction stream. A trap is synchronous and deliberate — a system call or a debugger breakpoint — and resumes after the trapping instruction. A fault is synchronous and unintended, such as a page fault or a divide by zero; if the OS can fix the condition it re-executes the faulting instruction, otherwise it signals or kills the process.
23. What is a device driver? 2–5 yrs
A device driver is the kernel component that translates the OS's generic device interface — read a block, send a packet — into the specific register writes and interrupt handling a particular piece of hardware needs. It exists so the rest of the kernel can treat all disks or all network cards alike. Because drivers run privileged and are written by hardware vendors, they are historically the largest source of kernel crashes.
24. What is a virtual machine and how does a hypervisor relate to the OS? Senior
A virtual machine is a software-created illusion of a complete computer, so an unmodified guest OS can run on it believing it owns the hardware. A type-1 hypervisor runs directly on the metal and schedules guests as the OS schedules processes; a type-2 hypervisor runs as an application on a host OS. Hardware virtualisation extensions give the hypervisor a privilege level below the guest kernel so guest privileged instructions trap to it cleanly.
25. What is the difference between a container and a virtual machine? Senior
A virtual machine virtualises the hardware and runs a complete guest kernel, so isolation is strong and the overhead is a full OS per instance. A container virtualises the operating system: processes share the host kernel but get separate namespaces for the file system, process tree, users and network, plus cgroup limits on CPU and memory. Containers start in milliseconds and pack far denser; the trade-off is that a kernel vulnerability is shared by every container on the host.
Processes and Threads
26. What is the difference between a process and a thread? Fresher
A process is an independent program in execution with its own memory space (code, data, heap, stack), while a thread is a lightweight unit of execution that runs inside a process. Threads of the same process share its code, data, and heap but each has its own stack and registers. Because they share memory, threads communicate more easily and context-switch faster than separate processes.
27. What are the different states of a process? Fresher
A process typically moves through five states: new (being created), ready (waiting to be assigned to the CPU), running (instructions are executing), waiting/blocked (waiting for I/O or an event), and terminated (finished execution). The OS scheduler moves processes between the ready, running, and waiting states.
28. What transitions can a process make between states, and what causes each? 2–5 yrs
New to ready when admission control lets it in; ready to running when the scheduler dispatches it; running to ready on preemption, either a timer expiry or a higher-priority arrival; running to waiting when it issues a blocking request such as I/O; waiting to ready when the event completes; and running to terminated on exit. Note there is no waiting-to-running edge — a woken process must go back through the ready queue and be scheduled.
29. What is a Process Control Block? Fresher
The PCB is the kernel data structure that represents a process: its identifier, current state, saved program counter and registers, scheduling information such as priority, memory management data like page table pointers, accounting data, and the open file table. It is the object the scheduler manipulates, and a context switch is essentially saving the CPU into one PCB and loading it from another. The PCB lives in kernel memory precisely so a user process cannot alter its own priority or permissions.
30. What are the segments of a process address space? Fresher
The text segment holds the executable instructions and is read-only and shareable; the data segment holds initialised globals; the BSS holds uninitialised globals zeroed at load; the heap grows upward for dynamic allocation; and the stack grows downward for call frames and locals. Threads share text, data and heap and get their own stack, which is exactly why a pointer to a local variable must never outlive its frame.
31. What is a context switch? Fresher
A context switch is the act of saving the state (registers, program counter, etc.) of the currently running process or thread and loading the saved state of another so the CPU can switch execution between them. It is what enables multitasking, but it is pure overhead — no useful work is done during the switch. Excessive context switching can hurt performance.
32. Why is a context switch expensive, and what makes a process switch costlier than a thread switch? 2–5 yrs
The direct cost is saving and restoring registers and kernel state, typically a few microseconds. The larger indirect cost is cache and branch-predictor pollution: the new task finds a cold cache and runs slowly for a while. Switching between processes adds an address space change, which means swapping page table roots and, without tagged TLB entries, flushing the TLB — threads in the same process skip that, which is why thread switches are noticeably cheaper.
33. What are the advantages and disadvantages of multithreading? 2–5 yrs
Advantages: responsiveness, since one thread can block on I/O while another serves the user; cheap sharing, since threads share the heap with no IPC; lower creation and switching cost than processes; and real parallelism across cores. Disadvantages: shared mutable state brings race conditions and deadlocks, debugging is much harder because bugs are timing-dependent, and one thread that corrupts memory or crashes takes the whole process down.
34. What is the difference between user-level and kernel-level threads? 2–5 yrs
User-level threads are managed by a library in user space, so creating and switching them is fast and needs no kernel involvement, but the kernel sees one schedulable entity — so one blocking system call stalls every thread and they cannot use multiple cores. Kernel-level threads are scheduled by the OS, so they block and run in parallel independently, at the cost of a system call for each operation. Most modern systems map one user thread to one kernel thread.
35. What are the many-to-one, one-to-one, and many-to-many threading models? Senior
Many-to-one maps many user threads onto one kernel thread: cheap but no parallelism and any blocking call stalls all of them. One-to-one gives each user thread its own kernel thread, so it blocks and runs independently but the count is limited by kernel resources — this is what Linux and Windows use. Many-to-many multiplexes M user threads over N kernel threads, combining cheap threads with real parallelism at the price of a complex scheduler, and it is how goroutines and modern virtual threads work.
36. What is a daemon or background process? 2–5 yrs
A daemon is a long-running process with no controlling terminal that provides a service — logging, scheduling, listening on a port. It is typically started at boot by the init system, detaches from its parent session so a logged-out user does not kill it, and reports through log files rather than standard output. On Windows the equivalent concept is a service.
37. What is a zombie process? 2–5 yrs
A zombie is a process that has terminated but whose entry remains in the process table because its parent has not yet collected the exit status with wait(). It holds no memory or CPU, only a table slot and its exit code. A few are normal and transient; a growing pile means the parent is buggy and can eventually exhaust process IDs. Killing a zombie does nothing — you fix or restart the parent.
38. What is an orphan process? 2–5 yrs
An orphan is a process whose parent exited first. The kernel re-parents it to the init process (PID 1), which reaps it when it eventually terminates, so orphans do not leak the way zombies do. Deliberately orphaning a child by forking twice is a classic way to daemonise a process.
39. What does fork() do, and what does it return? 2–5 yrs
fork() creates a new process that is a near-duplicate of the caller, with a copy of its address space, file descriptors and registers. It returns twice: zero in the child and the child's PID in the parent, which is how the same code path distinguishes them; a negative value means the fork failed. Modern kernels implement the copy with copy-on-write, so the pages are shared read-only until one side writes.
40. What is the difference between fork() and exec()? 2–5 yrs
fork() creates a new process; exec() replaces the current process image with a different program, keeping the same PID and (unless marked close-on-exec) the same open file descriptors. Neither alone starts a new program: the shell forks and then calls exec in the child, which is exactly why the child can set up redirections between the two calls before the new program ever runs.
41. What is copy-on-write and why does it matter for fork? Senior
Copy-on-write marks the parent's pages read-only and shared with the child instead of duplicating them, then copies a page only when either side writes to it. It makes fork cheap and near-constant time regardless of address space size, and it costs nothing extra when the child immediately calls exec and discards the image. The catch is that memory accounting becomes optimistic — a forked child that starts writing widely can trigger an out-of-memory condition long after the fork returned successfully.
42. What is the difference between concurrency and parallelism? Senior
Concurrency is a structuring property: multiple tasks are in progress over overlapping periods, which is achievable on a single core by interleaving. Parallelism is an execution property: multiple tasks literally run at the same instant on different cores. Concurrency is about dealing with many things at once, parallelism about doing many things at once — a concurrent design is what makes parallelism possible when cores are available.
43. What is a thread pool and why use one? 2–5 yrs
A thread pool keeps a fixed set of worker threads alive and feeds them tasks from a queue, instead of creating a thread per task. It removes repeated creation and teardown cost, and — more importantly — it bounds concurrency, so a burst of ten thousand requests does not create ten thousand threads and thrash the scheduler. The tuning question is pool size: roughly the core count for CPU-bound work, and considerably more for I/O-bound work where threads spend their time blocked.
CPU Scheduling
44. What are the common CPU scheduling algorithms? Fresher
Key algorithms include First-Come-First-Served (FCFS), which runs processes in arrival order; Shortest Job First (SJF), which picks the process with the smallest burst time; Round Robin (RR), which gives each process a fixed time quantum in turn; and Priority scheduling, which runs the highest-priority process first. FCFS can cause the convoy effect, SJF can starve long jobs, and Round Robin is preemptive and good for time-sharing systems.
45. What is the goal of CPU scheduling? Fresher
To keep the CPU busy while meeting the system's service goals. The usual metrics are CPU utilisation and throughput (maximise), and turnaround time, waiting time and response time (minimise), plus fairness and predictability. These conflict — the schedule with the best average turnaround is usually terrible for interactive response — so the right algorithm depends on whether the machine is a batch server, a desktop, or a real-time controller.
46. What is the difference between turnaround time, waiting time, and response time? Fresher
Turnaround time is completion time minus arrival time — the total time in the system. Waiting time is the part of that spent sitting in the ready queue, so turnaround minus burst time. Response time is from arrival until the process first gets the CPU, which is the metric interactive users actually feel. Round robin deliberately sacrifices average turnaround to keep response time low.
47. What is the difference between preemptive and non-preemptive scheduling? 2–5 yrs
Non-preemptive scheduling lets a process keep the CPU until it blocks or exits, which is simple and has low overhead but lets one long job hold up everyone. Preemptive scheduling can take the CPU away on a timer interrupt or when a higher-priority process becomes ready, which gives responsiveness and prevents monopolisation. The price is more context switches and the need for kernel data structures to be protected against being interrupted mid-update.
48. What are the long-term, short-term, and medium-term schedulers? Fresher
The long-term (job) scheduler decides which jobs are admitted into memory, controlling the degree of multiprogramming, and runs infrequently. The short-term (CPU) scheduler picks which ready process runs next and runs every few milliseconds, so it must be fast. The medium-term scheduler swaps processes out of memory and back in to relieve pressure, which is how the system reacts to thrashing.
49. What is the dispatcher? Fresher
The dispatcher is the module that actually hands the CPU to the process the short-term scheduler selected: it performs the context switch, switches to user mode, and jumps to the right instruction in the program. Dispatch latency — the time from stopping one process to starting the next — is pure overhead, and keeping it small and bounded is critical in real-time systems.
50. How does First-Come-First-Served scheduling work and what is wrong with it? Fresher
FCFS runs processes in arrival order using a simple FIFO queue, and it is non-preemptive. It is trivially fair in the arrival sense and has minimal overhead, but average waiting time is poor and highly sensitive to order. Its signature failure is the convoy effect: one long CPU-bound job at the head makes every short and I/O-bound job behind it wait, leaving devices idle while the queue backs up.
51. What is the convoy effect? 2–5 yrs
The convoy effect is when a long-running process holds a resource — classically the CPU under FCFS — and a queue of short processes piles up behind it. Throughput collapses because the I/O devices those short jobs would have driven sit idle, and then they all become ready at once and convoy again behind the next long job. Preemption with a time quantum is the standard cure.
52. How does Shortest Job First scheduling work? 2–5 yrs
SJF selects the ready process with the smallest next CPU burst. It is provably optimal for average waiting time among non-preemptive algorithms, which is why it is the theoretical benchmark. The practical problem is that the next burst length is not known in advance, so real systems estimate it with an exponential average of past bursts, and long jobs can starve if short ones keep arriving.
53. What is Shortest Remaining Time First? 2–5 yrs
SRTF is the preemptive version of SJF: when a new process arrives whose burst is shorter than the remaining time of the running process, the running process is preempted. It gives an even better average waiting time than SJF, at the cost of more context switches and worse starvation for long jobs, since a steady stream of short arrivals can keep a long job from ever finishing.
54. How does Round Robin scheduling work? Fresher
Round robin gives each ready process a fixed time quantum in turn; when the quantum expires the process is preempted and moved to the tail of the ready queue. It is preemptive FCFS with a timer, it guarantees a bounded response time of roughly (n-1) times the quantum, and it cannot starve anyone. Its average turnaround time is usually worse than SJF, which is the deliberate trade for interactivity.
55. How do you choose the time quantum in Round Robin? 2–5 yrs
Too large and round robin degenerates into FCFS, losing responsiveness; too small and the system spends a significant fraction of its time context switching rather than working. The usual rule of thumb is that the quantum should be large enough that around 80 percent of CPU bursts finish inside it, and it must be well above the context switch cost — typical values are 10 to 100 milliseconds against switches measured in microseconds.
56. How does priority scheduling work, and what is its main problem? 2–5 yrs
Each process gets a priority number and the scheduler always runs the highest-priority ready process, either preemptively or not. Priorities can be set internally from measured behaviour or externally from policy. The main problem is indefinite blocking, or starvation: a low-priority process may never run while higher-priority work keeps arriving. Ageing — gradually raising the priority of processes that have waited a long time — is the standard fix.
57. What is starvation and how is it prevented? 2–5 yrs
Starvation is a runnable process being denied a resource indefinitely because the policy keeps favouring others — low-priority processes under strict priority scheduling, long jobs under SJF, or a writer perpetually blocked by a stream of readers. It is prevented with ageing, with a fairness guarantee such as round robin's bounded wait, or with FIFO ordering inside each priority level. Note that starvation is not deadlock: a starving process could run, it just never gets chosen.
58. What is multilevel queue scheduling? 2–5 yrs
Multilevel queue scheduling permanently partitions the ready queue into several queues by process class — for example interactive, batch, and system — each with its own algorithm, such as round robin for interactive and FCFS for batch. Scheduling then happens between the queues too, usually by fixed priority or by allocating each a share of CPU time. Its rigidity is the flaw: a process cannot move between queues, so a misclassified job stays misclassified.
59. What is multilevel feedback queue scheduling? 2–5 yrs
It is multilevel queue scheduling where processes can move between queues based on observed behaviour. A new process starts in the highest-priority queue with a short quantum; if it uses the whole quantum it is demoted to a longer-quantum, lower-priority queue, and if it blocks early it stays high. This automatically favours interactive and I/O-bound work without anyone declaring what a process is, and ageing promotes long-waiting jobs to prevent starvation.
60. How do modern general-purpose schedulers differ from textbook algorithms? Senior
They target proportional fairness rather than raw turnaround. Linux's CFS tracks each task's virtual runtime and always runs the one that has received least, weighted by nice value, so shares are honoured without fixed time slices; the newer EEVDF scheduler adds explicit latency guarantees. They also add per-core run queues with work stealing, and awareness of NUMA topology and heterogeneous cores, because migrating a task to a cold cache or a distant memory node can cost more than waiting.
61. What is processor affinity and why does it matter? Senior
Processor affinity is the tendency, or the explicit constraint, to keep a thread running on the same core. It matters because a migrated thread arrives to a cold L1 and L2 cache and, on a NUMA system, may end up far from the memory it allocated. Soft affinity is the scheduler's preference; hard affinity is a pinning API. The trade-off against affinity is load imbalance, where one core queues work while another idles.
62. What is priority inversion and how is it solved? Senior
Priority inversion is when a high-priority task waits on a lock held by a low-priority task, and a medium-priority task that needs no lock preempts the low-priority holder — so the high-priority task is effectively blocked by an unrelated medium one. The famous case is the Mars Pathfinder resets. The fixes are priority inheritance, where the holder temporarily inherits the waiter's priority, and the priority ceiling protocol, which raises the holder to the highest priority that can ever request the lock.
63. What are hard and soft real-time scheduling algorithms? Senior
Rate-monotonic scheduling assigns static priorities inversely to period — the more frequent the task, the higher its priority — and is optimal among fixed-priority schemes, with a utilisation bound of about 69 percent for large task sets. Earliest Deadline First assigns priority dynamically to whichever deadline is nearest and can schedule any set up to 100 percent utilisation, but it degrades unpredictably if it does overload. Both require known worst-case execution times, which is the hard part in practice.
Interprocess Communication
64. What is interprocess communication and why is it needed? Fresher
IPC is the set of mechanisms the OS provides for processes to exchange data and coordinate, since each process has an isolated address space and cannot simply read another's memory. It is needed for pipelines, client-server designs, and any system split into cooperating processes for isolation or modularity. The two broad families are shared memory, which is fast but requires you to handle synchronisation, and message passing, which is safer but pays a copy through the kernel.
65. What is the difference between shared memory and message passing? 2–5 yrs
With shared memory the kernel maps one physical region into two address spaces and then steps out of the way, so transfers run at memory speed but the processes must coordinate access themselves with semaphores or mutexes. With message passing every send and receive is a system call that copies data through the kernel, which is slower per byte but needs no explicit synchronisation and works unchanged across machines. Shared memory suits high-volume local data; message passing suits control and distributed systems.
66. What is a pipe? Fresher
A pipe is a unidirectional in-kernel byte-stream buffer with a read end and a write end, used to connect the output of one process to the input of another. An anonymous pipe only works between related processes, because the descriptors are inherited across fork, which is exactly how a shell implements the vertical bar. Writes block when the buffer is full and reads block when it is empty, giving flow control for free.
67. What is the difference between an anonymous pipe and a named pipe? 2–5 yrs
An anonymous pipe exists only as file descriptors and can therefore be shared only with related processes through fork. A named pipe, or FIFO, has a path in the file system, so any two unrelated processes with the right permissions can open it by name. Both are unidirectional byte streams with the same blocking semantics; the FIFO simply adds a rendezvous point that outlives the processes.
68. What is a message queue in IPC? 2–5 yrs
A message queue is a kernel-maintained list of discrete messages, each with a type or priority, that processes can send to and receive from asynchronously. Unlike a pipe it preserves message boundaries, the sender need not wait for a receiver, and a receiver can selectively pick messages by type. The costs are a copy in each direction and a fixed kernel limit on queue size.
69. What is a socket, and when is it used instead of a pipe? 2–5 yrs
A socket is a bidirectional endpoint for communication that works both between processes on one machine (Unix domain sockets) and across a network (TCP or UDP). You use it instead of a pipe when you need two-way traffic, unrelated processes, many concurrent clients, or the option of moving a component to another host without changing the code. The price relative to a pipe is a heavier protocol stack and more setup.
70. What is a signal? 2–5 yrs
A signal is an asynchronous software interrupt delivered to a process to notify it of an event — SIGINT from Ctrl+C, SIGSEGV for an invalid access, SIGCHLD when a child exits. The process can accept the default action, ignore it, or install a handler, though SIGKILL and SIGSTOP cannot be caught. Handlers run at an arbitrary point in the program, so only async-signal-safe functions may be called inside one.
71. What is a remote procedure call? Senior
An RPC makes a call to a procedure in another address space or on another machine look like a local function call. Client and server stubs handle marshalling the arguments into a message, transmitting it, and unmarshalling the result. The abstraction leaks in ways local calls do not — latency, partial failure, and the ambiguity of a timeout where you cannot tell whether the work happened — which is why RPC APIs need explicit timeouts, retries, and idempotency.
72. What is memory-mapped I/O in the context of files? Senior
Memory mapping asks the OS to map a file's contents directly into the process address space, so reads and writes become ordinary memory accesses served by the page fault handler rather than read and write system calls. It avoids the copy from kernel buffer to user buffer, and mapping the same file shared gives several processes a shared memory region backed by disk. The pitfalls are that an I/O error surfaces as a signal rather than an error return, and that writes are flushed on the kernel's schedule unless you sync explicitly.
Process Synchronisation
73. What is a race condition? Fresher
A race condition is when the result of a computation depends on the unpredictable interleaving of concurrent operations on shared data. The classic case is two threads doing counter = counter + 1: each reads the same old value, adds one, and writes back, so one increment vanishes because the read-modify-write is not atomic. Races are pernicious because they are timing-dependent and often disappear under a debugger.
74. What is the critical section problem? Fresher
The critical section is the part of a program that accesses shared resources and must not be executed by more than one process at a time. The critical section problem is designing a protocol that lets processes cooperate while satisfying three requirements: mutual exclusion, progress (a process not in its critical section cannot block others), and bounded waiting (no process waits indefinitely). Solutions use locks, semaphores, or algorithms like Peterson's.
75. What are the three requirements a correct critical section solution must satisfy? 2–5 yrs
Mutual exclusion: at most one process is inside the critical section at a time. Progress: if no one is inside, the choice of who enters next cannot be postponed indefinitely, and processes running only in their remainder sections must not participate in that decision. Bounded waiting: there is a limit on how many times others can enter after a process has requested entry, which is what rules out starvation.
76. What is Peterson's solution? 2–5 yrs
Peterson's algorithm gives mutual exclusion for two processes using only shared variables — a flag array signalling intent and a turn variable breaking ties — with no special hardware instruction. It satisfies all three critical-section requirements and is the standard teaching example. It is not used in practice because it does not generalise cleanly beyond two processes and, more importantly, modern CPUs and compilers reorder memory operations, so it needs explicit memory barriers to be correct on real hardware.
77. What is a mutex? 2–5 yrs
A mutex is a lock that permits exactly one thread into a critical section at a time, with ownership: only the thread that locked it may unlock it. That ownership is what allows recursion support, priority inheritance and error checking on misuse. A thread that finds the mutex held blocks and is put on a wait queue, so the CPU goes to someone else rather than spinning.
78. What is the difference between a semaphore and a mutex? Fresher
A mutex is a locking mechanism that allows only one thread into a critical section at a time, and it has ownership — only the thread that locked it can unlock it. A semaphore is a signaling mechanism with an integer counter; a counting semaphore can allow multiple threads up to a set limit, and a binary semaphore (value 0/1) behaves like a lock but without ownership. In short, a mutex is for mutual exclusion while a semaphore is for signaling and managing access to a pool of resources.
79. What is the difference between a binary semaphore and a counting semaphore? 2–5 yrs
A binary semaphore takes only 0 or 1 and is used to enforce mutual exclusion or to signal a single event. A counting semaphore is initialised to N and permits up to N concurrent holders, which models a pool of identical resources such as database connections or buffer slots. Both use the same wait and signal operations; only the initial value differs, and getting that initial value wrong is the most common semaphore bug after forgetting to signal.
80. What are the wait and signal operations on a semaphore? 2–5 yrs
wait (also P or down) decrements the semaphore, and if the result is negative the calling process blocks on the semaphore's queue. signal (also V or up) increments it, and if a process is waiting, one is woken. Both must be atomic — implemented with a hardware instruction or by briefly disabling interrupts — because a semaphore that can itself be preempted mid-update reintroduces exactly the race it was meant to prevent.
81. What is a spinlock and when is it preferable to a blocking lock? 2–5 yrs
A spinlock makes a waiting thread loop testing the lock rather than sleeping. It is preferable when the expected wait is shorter than the cost of two context switches — inside a kernel on a multiprocessor, or around a handful of instructions — and it is mandatory in contexts where sleeping is illegal, such as an interrupt handler. It is a bad choice on a single core, where the spinner burns the entire quantum the holder needs to make progress.
82. What is busy waiting and why is it a problem? 2–5 yrs
Busy waiting is repeatedly checking a condition in a loop instead of blocking until it changes. It wastes CPU cycles that another runnable process could use, and on a single-core system it actively prevents the process that would satisfy the condition from running. It is acceptable only when the wait is very short and the alternative context switch would cost more, which is exactly the spinlock case.
83. What is a monitor? 2–5 yrs
A monitor is a higher-level synchronisation construct that bundles shared data, the procedures that operate on it, and the lock, so mutual exclusion is automatic — only one thread is active inside the monitor at a time. Condition variables inside the monitor provide wait and signal so a thread can release the lock and sleep until some predicate holds. It is safer than raw semaphores because you cannot forget the matching release; Java's synchronized plus wait/notify is a monitor.
84. What is a condition variable and how does it differ from a semaphore? 2–5 yrs
A condition variable is a wait queue associated with a lock: a thread atomically releases the lock and sleeps until another thread signals the condition, then reacquires the lock before continuing. Unlike a semaphore it has no memory — signalling when nobody is waiting is lost, whereas a semaphore's count records it. That is why condition variable waits always sit inside a loop rechecking the predicate, which also handles spurious wakeups.
85. What is an atomic instruction such as test-and-set or compare-and-swap? Senior
These are hardware instructions that read a memory location and conditionally write it back in one uninterruptible step, which is the primitive every higher-level lock is built on. Test-and-set writes 1 and returns the old value; compare-and-swap writes a new value only if the current one matches an expected one, and reports whether it succeeded. CAS is the more powerful of the two because it enables lock-free algorithms, at the cost of the ABA problem when a value is changed and changed back.
86. What is the difference between a lock and a lock-free algorithm? Senior
A lock-based algorithm makes waiters block until the holder releases, so a thread descheduled inside the critical section stalls everyone. A lock-free algorithm uses atomic operations such as compare-and-swap in a retry loop and guarantees that some thread always makes progress regardless of what the others do, which removes deadlock and priority inversion. The trade-off is that lock-free code is far harder to write correctly, especially around memory ordering and reclamation.
87. What is a reader-writer lock? Senior
A reader-writer lock allows any number of concurrent readers or a single exclusive writer, exploiting the fact that concurrent reads do not conflict. It pays off when reads vastly outnumber writes and the critical sections are long enough to amortise the extra bookkeeping. The design decision is the policy: reader-preferring maximises read throughput but can starve writers, while writer-preferring protects writers at some cost to reader concurrency.
Classic Synchronisation Problems
88. What is the producer-consumer problem? 2–5 yrs
A producer generates items into a bounded buffer and a consumer removes them; the producer must block when the buffer is full and the consumer when it is empty, with no two processes touching the buffer at once. The standard solution uses three semaphores: a counting semaphore for empty slots, one for full slots, and a mutex for the buffer itself. The classic bug is acquiring the mutex before the counting semaphore, which deadlocks a full buffer because the consumer cannot get in to drain it.
89. What is the readers-writers problem? 2–5 yrs
Many processes want to read a shared object and some want to write it; readers may proceed concurrently, but a writer needs exclusive access. The first formulation gives readers priority — no reader waits unless a writer already holds the lock — which can starve writers indefinitely under a steady read stream. The second gives waiting writers priority, which can starve readers. A fair variant queues both in arrival order, trading a little throughput for no starvation.
90. What is the dining philosophers problem? 2–5 yrs
Five philosophers sit around a table with one fork between each pair, and each needs both neighbouring forks to eat. If every philosopher picks up their left fork simultaneously, all four Coffman conditions hold and the table deadlocks. It is the canonical illustration that a correct-looking per-process rule can produce global deadlock, and it is also used to show livelock when everyone politely puts a fork down and retries in lockstep.
91. How do you solve the dining philosophers problem? 2–5 yrs
Any solution breaks one Coffman condition. Impose a global ordering so every philosopher picks up the lower-numbered fork first — this breaks circular wait and is the general lock-ordering rule used in real systems. Alternatively allow at most four philosophers at the table at once, which makes the wait graph acyclic, or make each philosopher acquire both forks atomically under a mutex, which breaks hold-and-wait. Making one philosopher left-handed is the asymmetric version of the ordering fix.
92. What is the sleeping barber problem? Senior
A barber sleeps when there are no customers, cuts hair when there are, and customers leave if all waiting chairs are taken. It models a server with a bounded request queue and captures the wake-up race: a customer must not conclude the barber is asleep and go to sleep himself at the same moment the barber concludes the shop is empty. The solution uses semaphores for customers, barbers, and a mutex over the seat count.
93. What is the lost wakeup problem? Senior
A lost wakeup happens when a thread checks a condition, finds it false, and is preempted before it sleeps; another thread makes the condition true and signals, and then the first thread sleeps forever waiting for a notification that already fired. It is why the release-lock-and-sleep step of a condition variable must be atomic, and why you always wait in a loop that rechecks the predicate rather than in an if.
94. What is livelock, and how does it differ from deadlock? Senior
In deadlock the processes are blocked and doing nothing. In livelock they are actively running and changing state but making no progress, because each keeps reacting to the others — two threads that both release their lock on detecting contention and immediately retry in lockstep, or two people repeatedly stepping aside in the same direction in a corridor. The usual fix is randomised backoff, which breaks the symmetry.
Deadlocks
95. What is a deadlock and what are its four necessary conditions? Fresher
A deadlock is a situation where two or more processes are each waiting for a resource held by another, so none can proceed. It can only occur when all four Coffman conditions hold simultaneously: mutual exclusion, hold and wait, no preemption, and circular wait. Breaking any one of these conditions prevents deadlock.
96. What does each of the four Coffman conditions mean? 2–5 yrs
Mutual exclusion: at least one resource is non-shareable, so only one process can hold it. Hold and wait: a process holding a resource is allowed to request another. No preemption: a resource can only be released voluntarily by its holder. Circular wait: there is a cycle of processes where each waits for a resource the next one holds. All four must hold at once, which is why prevention strategies each target exactly one.
97. How can deadlocks be handled — prevention, avoidance, and the banker's algorithm? 2–5 yrs
Deadlocks can be handled by prevention (designing the system so one of the four conditions can never hold), avoidance (granting resources only if the system stays in a safe state), or detection and recovery. The banker's algorithm is an avoidance technique: before granting a request it simulates the allocation and grants it only if a safe sequence still exists in which every process can finish.
98. How does deadlock prevention differ from deadlock avoidance? 2–5 yrs
Prevention is structural: you design the system so one of the four conditions can never hold — for example, requiring all resources to be requested at once, or imposing a global lock ordering — and it needs no runtime information. Avoidance is dynamic: it allows the conditions in principle but examines each request against declared maximum needs and denies any that could lead to an unsafe state. Prevention costs utilisation; avoidance costs runtime analysis and requires knowing maximum demands up front.
99. How do you break each of the four conditions to prevent deadlock? 2–5 yrs
Mutual exclusion can sometimes be removed by making a resource shareable or by spooling it, though for a printer or a lock it is inherent. Hold and wait is broken by requiring a process to acquire everything at once, or to release all held resources before requesting more — at the cost of low utilisation and possible starvation. No preemption is broken by forcibly reclaiming resources from a waiting process, which suits CPU registers and memory but not a half-written file. Circular wait is broken by numbering resources and requiring requests in increasing order, which is the practical technique real code uses.
100. What is a safe state? 2–5 yrs
A state is safe if there exists at least one sequence of all processes such that each can obtain its declared maximum resources, run, and release — even if every process demands its maximum. Every safe state is deadlock-free, but an unsafe state is not necessarily a deadlock; it merely means the system can no longer guarantee escape. Avoidance algorithms work by never leaving the safe region, which is why they are conservative and sometimes deny requests that would in fact have been fine.
101. How does the banker's algorithm actually work? Senior
It maintains Available, Max, Allocation and Need matrices. On a request it first checks the request does not exceed the process's need or what is available, then pretends to grant it and runs the safety algorithm: repeatedly find a process whose Need fits within Available, assume it finishes and returns its allocation, and mark it done. If every process can be marked done, a safe sequence exists and the grant stands; otherwise the state is rolled back and the requester blocks. Its cost is O(n squared times m) per request, which is why real kernels do not use it.
102. Why is the banker's algorithm rarely used in real systems? Senior
It requires every process to declare its maximum resource needs in advance, which general-purpose programs simply do not know; it assumes a fixed number of resources and processes; and it runs an O(n squared times m) safety check on every request. It is also conservative, denying safe-in-practice requests. Real systems use lock ordering for prevention, or ignore deadlock entirely and rely on timeouts and restarts — the ostrich approach.
103. How is deadlock detected? 2–5 yrs
The system builds a wait-for graph — an edge from each process to the process holding the resource it wants — and periodically searches for a cycle; with single-instance resources a cycle is a deadlock. With multiple instances per resource type, a cycle is only a necessary condition, so a matrix-based algorithm resembling the banker's safety check is used instead. The design question is frequency: checking often costs CPU, checking rarely means deadlocked processes sit idle longer.
104. How does a system recover from deadlock? 2–5 yrs
Either terminate processes or preempt resources. Termination can abort all deadlocked processes, which is certain but expensive, or abort them one at a time, rechecking after each — choosing the victim by priority, elapsed runtime, resources held, or how much work would be lost. Preemption takes a resource from one process and gives it to another, which requires rolling that process back to a safe checkpoint and raises the risk of always victimising the same process, so victim selection must include a starvation guard.
105. What is a resource allocation graph? 2–5 yrs
It is a directed graph with process nodes and resource nodes, where a request edge runs from a process to a resource and an assignment edge from a resource instance to a process. If every resource type has one instance, a cycle in the graph means deadlock; if some have multiple instances, a cycle is necessary but not sufficient. It is the standard tool for reasoning about a small deadlock scenario in an interview.
106. What is the ostrich algorithm? Senior
The ostrich algorithm is deliberately ignoring the possibility of deadlock, on the grounds that it is rare and that prevention or avoidance would cost more in performance and restricted functionality than the occasional reboot. Most general-purpose operating systems, including Linux and Windows, take this approach for user-level resource deadlocks. It is a rational engineering choice when the expected cost of handling exceeds the expected cost of the failure.
107. What is the practical way to avoid deadlocks in application code? Senior
Impose and document a global lock acquisition order and never take locks out of that order; hold locks for the shortest possible span and never call unknown code — a callback, a virtual method — while holding one; prefer a single coarser lock over two fine-grained ones unless contention proves otherwise; and use timed lock attempts so a failure surfaces as an error rather than a hang. Lock ordering is the one that eliminates the entire class, because it makes circular wait impossible.
Memory Management
108. What does the memory manager of an operating system do? Fresher
It tracks which parts of physical memory are in use and by whom, allocates and frees space as processes start and end, provides each process with an address space isolated from the others, and decides what to keep in RAM versus what to move to disk. It also enforces protection, so one process cannot read or write another's pages, which is the mechanism behind the isolation user-mode gives you.
109. What is the difference between logical and physical address space? Fresher
A logical (virtual) address is what the CPU generates while a program runs, and it is meaningful only within that process. A physical address is the actual location in RAM. The memory management unit translates one to the other at every access, which is what lets two processes both use address 0x400000 without colliding and what makes relocation and paging invisible to the program.
110. What is the memory management unit? 2–5 yrs
The MMU is the hardware that translates virtual addresses to physical ones on every memory access, walking the page tables and caching results in the TLB. It also enforces protection bits — read, write, execute, user versus kernel — and raises a page fault when a translation is missing or a permission is violated. Because translation sits in the critical path of every load and store, it has to be hardware; a software implementation would be orders of magnitude slower.
111. What is contiguous memory allocation, and what are first fit, best fit, and worst fit? 2–5 yrs
Contiguous allocation gives each process a single continuous block of physical memory, tracked as a set of holes. First fit takes the first hole large enough and is fastest; best fit takes the smallest sufficient hole, which minimises the leftover but leaves many unusable slivers and requires scanning the list; worst fit takes the largest hole so the remainder stays useful, but it consumes big blocks fastest. In practice first fit and best fit both perform better than worst fit, and first fit usually wins on speed.
112. What is the difference between internal and external fragmentation? Fresher
Internal fragmentation is wasted space inside an allocated block, when a fixed-size allocation is larger than the memory the process actually needs — common with paging. External fragmentation is wasted space outside allocated blocks, when free memory is split into small non-contiguous holes that together are large enough but cannot satisfy a request — common with variable-size allocation and segmentation. Compaction and paging are common ways to reduce external fragmentation.
113. What is compaction and why is it expensive? 2–5 yrs
Compaction shuffles allocated blocks together to merge scattered free holes into one large usable region, eliminating external fragmentation. It is expensive because it copies potentially gigabytes of memory and every process must be stopped and its addresses fixed up while it runs, so it needs dynamic relocation hardware to be possible at all. Paging is preferred precisely because it removes the need for contiguity, and therefore for compaction.
114. What is paging? Fresher
Paging divides the virtual address space into fixed-size pages and physical memory into frames of the same size, then maps any page to any frame through a page table. Because the mapping is arbitrary, a process's memory need not be physically contiguous, which eliminates external fragmentation entirely. The costs are internal fragmentation in the last page, the memory the page tables themselves consume, and an extra memory reference per access unless the TLB hits.
115. What is the difference between paging and segmentation? Fresher
Paging divides memory into fixed-size blocks called pages (and physical frames), so it suffers from internal fragmentation but no external fragmentation, and it is invisible to the programmer. Segmentation divides memory into variable-size logical units such as code, stack, and data, which can cause external fragmentation but maps naturally to the program's logical structure. Paging is the simpler hardware view; segmentation is the more programmer-friendly logical view, and some systems combine both.
116. What is segmentation with paging? 2–5 yrs
The address is first resolved through a segment table to find a segment's own page table, then the page number indexes that table to reach a frame. You get segmentation's logical structure and per-segment protection along with paging's freedom from external fragmentation and contiguity. The cost is two levels of translation, which is why the TLB matters even more; the x86 architecture historically implemented exactly this scheme.
117. How is a virtual address translated in a paged system? 2–5 yrs
The address splits into a page number and an offset determined by the page size — with 4 KB pages the low 12 bits are the offset. The page number indexes the page table to yield a frame number, and the physical address is that frame number concatenated with the unchanged offset. The offset never goes through translation, which is why page size must be a power of two and why translation is a bit-field operation rather than arithmetic.
118. What is a page table entry and what does it contain? 2–5 yrs
It holds the frame number plus control bits: valid/invalid (is the page resident), protection bits for read, write and execute, a user/supervisor bit, a dirty bit set when the page is written, and a referenced or accessed bit used by replacement algorithms. The dirty bit is what lets the OS skip writing an unmodified page back to disk on eviction, and the accessed bit is how LRU approximations get their information.
119. What is a Translation Lookaside Buffer? 2–5 yrs
The TLB is a small, fully associative hardware cache of recent virtual-to-physical page translations, typically a few dozen to a few thousand entries. Without it every memory access would need at least one extra access to read the page table, doubling the cost; with typical hit rates above 98 percent the average overhead falls to a few percent. A context switch invalidates it unless entries are tagged with an address space identifier, which is a large part of why process switches cost more than thread switches.
120. What is a multilevel page table and why is it needed? Senior
A single flat page table for a 64-bit address space would be astronomically large, and even a 32-bit space with 4 KB pages needs a 4 MB table per process, most of it unused. A multilevel table breaks the page number into several indices and pages the table itself, so only the branches covering allocated regions exist — an empty region is a single null entry at the top level. The cost is one memory reference per level on a TLB miss, which is why x86-64 four-level paging makes a miss expensive and why huge pages help.
121. What is an inverted page table? Senior
An inverted page table has one entry per physical frame rather than per virtual page, recording which process and virtual page currently occupy it, so its size is proportional to RAM instead of to the number of processes. It saves a great deal of memory but makes translation a search rather than an index, which requires a hash table to be practical and complicates shared memory, since one frame maps to several virtual pages. It is used on architectures such as PowerPC and IA-64.
122. What are huge pages and when do they help? Senior
Huge pages are page sizes far larger than the default — 2 MB or 1 GB on x86-64 — so one TLB entry covers much more memory. They help workloads with large working sets and poor locality, such as databases and in-memory analytics, where TLB misses and page walks are a measurable cost. The downsides are more internal fragmentation, higher latency to allocate a contiguous huge frame under memory pressure, and coarser granularity for swapping and copy-on-write.
123. What is swapping? 2–5 yrs
Swapping moves a whole process, or in modern systems selected pages, out of RAM to a backing store and later back in, so the system can run more processes than physically fit. Classic whole-process swapping is coarse and slow; demand paging refined it to page granularity, and the medium-term scheduler uses it as a pressure valve. Because disk is several orders of magnitude slower than RAM, heavy swapping is what turns into thrashing.
124. What is memory protection and how is it enforced? 2–5 yrs
Memory protection stops a process from reading or writing memory it does not own. It is enforced by the MMU on every access: a page not present in the process's page table cannot be named at all, and protection bits in each entry cover read, write, execute and privilege level. A violation raises a fault that the kernel turns into a segmentation fault. The no-execute bit is the same mechanism used to stop code executing from the stack or heap.
Virtual Memory and Paging
125. What is virtual memory? Fresher
Virtual memory is a technique that gives each process the illusion of a large, contiguous address space that may be larger than the physical RAM. The OS keeps only the actively used pages in RAM and stores the rest on disk (in a swap area or page file), bringing pages in on demand. This allows more and larger programs to run than would fit in physical memory.
126. What are the benefits of virtual memory beyond running larger programs? 2–5 yrs
It gives each process an isolated address space, which is the basis of memory protection; it lets programs start before they are fully loaded, improving startup time; it allows pages to be shared between processes, so one copy of a library serves everyone; and it makes copy-on-write fork cheap. It also frees the compiler and linker from worrying about where the program will physically sit.
127. What is demand paging? 2–5 yrs
Demand paging loads a page into memory only when it is first referenced, rather than loading the whole program up front. The page table marks non-resident pages invalid, and touching one raises a page fault the OS services by fetching the page. It reduces startup latency and physical memory use, since programs typically touch only a fraction of their address space, and it is what makes a virtual space larger than RAM workable.
128. What is a page fault? Fresher
A page fault occurs when a program accesses a page that is mapped in its virtual address space but is not currently loaded in physical memory. The OS traps the fault, fetches the required page from disk into a free frame (evicting another page if needed via a replacement algorithm), updates the page table, and resumes the instruction. Too many page faults can severely slow a program because disk access is far slower than RAM.
129. What is the difference between a minor and a major page fault? 2–5 yrs
A minor (soft) fault is resolved without disk I/O: the page is already in physical memory — in the page cache, in a shared mapping, or on the free list — and the kernel just fixes up the page table entry. A major (hard) fault requires reading from the backing store and costs milliseconds rather than microseconds. When someone says page faults are slow, they mean major faults; a process can take millions of minor faults and still run fine.
130. What is the effective access time with paging, and why does the fault rate matter so much? 2–5 yrs
Effective access time is (1 - p) times memory access time plus p times page fault service time, where p is the fault rate. Because a memory access is around 100 nanoseconds and a disk fault around 8 milliseconds, the fault path is roughly 80,000 times slower. A fault rate of just 1 in 1,000 already makes average access about 80 times worse, which is why replacement algorithms are judged on fault count alone.
131. What is page replacement and when does it happen? 2–5 yrs
When a page fault occurs and no free frame is available, the OS must choose a resident page to evict, write it back if its dirty bit is set, and reuse the frame. The choice is made by a page replacement algorithm, and the goal is simply to minimise total faults. Most systems keep a small pool of free frames maintained in the background so the fault path does not have to wait for a write-back.
132. How does FIFO page replacement work and what is its weakness? 2–5 yrs
FIFO evicts the page that has been resident longest, using a simple queue. It is trivial to implement and needs no hardware support, but age is a poor proxy for future use: a heavily used page loaded at startup gets evicted just because it is old. FIFO is also the algorithm that exhibits Belady's anomaly, where adding frames can increase the number of faults.
133. What is Belady's anomaly? 2–5 yrs
Belady's anomaly is the counter-intuitive result that giving a process more frames can produce more page faults, not fewer, under FIFO — the standard demonstration uses the string 1,2,3,4,1,2,5,1,2,3,4,5 with three versus four frames. It happens because FIFO's eviction order is not based on usage, so a larger memory can change the order in a way that discards pages sooner. Stack algorithms such as LRU and optimal cannot exhibit it, because their resident set with n frames is always a subset of the set with n+1.
134. What is the optimal page replacement algorithm? 2–5 yrs
The optimal algorithm, also called OPT or Belady's algorithm, evicts the page that will not be used for the longest time in the future, and it provably yields the minimum possible number of faults. It cannot be implemented because it requires knowledge of future references. Its value is as a benchmark: when you evaluate LRU or clock on a trace, OPT tells you how much room for improvement actually exists.
135. How does LRU page replacement work, and how is it approximated in practice? 2–5 yrs
LRU evicts the page that has gone unused for the longest time, on the assumption that recent use predicts near-future use. Exact LRU needs a timestamp or a stack update on every memory reference, which is far too expensive in hardware. Real systems approximate it: the reference bit gives second-chance and clock algorithms, and a shift register of reference bits gives additional-reference-bits LRU that ranks pages by recent history at a fraction of the cost.
136. What is the clock or second-chance algorithm? 2–5 yrs
Second chance is FIFO with a reprieve: when the oldest page comes up for eviction, if its reference bit is 1 the bit is cleared and the page goes to the back of the queue instead of being evicted. The clock algorithm implements this as a circular buffer with a hand that sweeps, clearing bits until it finds one already 0. It approximates LRU well at almost no cost, which is why real kernels use variants of it rather than true LRU.
137. What is the LFU algorithm and what is wrong with it? Senior
Least Frequently Used evicts the page with the smallest reference count, on the theory that heavily used pages should stay. The problem is that counts reflect the whole history: a page used intensively during startup keeps a high count long after it stops being needed, while a newly hot page is evicted because its count is still low. Practical variants age the counts by periodically halving them, which lets the metric follow phase changes.
138. What is thrashing? 2–5 yrs
Thrashing is a state where the system spends most of its time swapping pages in and out of memory rather than executing useful work, causing CPU utilization to collapse. It happens when there is too little physical memory for the active set of processes, so page faults occur constantly. It can be reduced by lowering the degree of multiprogramming, adding more RAM, or using the working-set model to manage page allocation.
139. Why does thrashing get worse once it starts? 2–5 yrs
Because the scheduler misreads the symptom. Faulting processes block on I/O, so CPU utilisation drops, so the long-term scheduler admits more processes to keep the CPU busy — which takes frames away from the already starved processes and raises the fault rate further. That feedback loop is why utilisation falls off a cliff rather than degrading gradually, and why the fix is to reduce, not increase, the degree of multiprogramming.
140. What is the working set model? 2–5 yrs
The working set of a process is the set of pages it has referenced in the most recent window of delta references, taken as an estimate of what it needs resident now. The OS sums the working set sizes of all processes and, if the total exceeds available frames, suspends a process to free memory. It directly targets thrashing by ensuring each running process has enough frames for its current locality, and the tuning difficulty is choosing delta.
141. What is locality of reference? 2–5 yrs
Locality is the empirical observation that programs do not access memory uniformly: temporal locality means a recently used address is likely to be used again soon, and spatial locality means addresses near a recently used one are likely to be used soon. Caches, prefetching, demand paging and the working set model all exist because of it. A program with poor locality — a random walk over a huge array — defeats all of them at once.
142. What is the difference between local and global page replacement? Senior
With local replacement a faulting process may only evict its own pages, so its frame allocation is fixed and its performance is predictable and unaffected by other processes' behaviour. With global replacement it may take a frame from any process, which gives better overall throughput because frames flow to whoever needs them, but one badly behaved process can starve the rest and performance becomes non-reproducible. Most systems use global replacement with per-process minimums.
143. What is prepaging, and what is the trade-off? Senior
Prepaging brings in a group of pages the OS expects to be needed rather than waiting for each fault, typically on process startup or resumption after a swap out. It amortises disk seek cost across many pages and avoids a burst of faults. The trade-off is straightforward: if a substantial fraction of the prepaged pages go unused, you have spent I/O bandwidth and frames on nothing, so the win depends on prediction accuracy.
144. What is a memory leak from the operating system's point of view? Senior
The OS sees a process whose resident and virtual set keep growing and are never returned. It does not know the memory is unreachable — that is a property of the program's data structures, not of the address space — so it keeps honouring the allocations until physical memory and swap are exhausted. At that point the allocator fails or the out-of-memory killer selects a victim, usually the largest consumer, which is often but not always the leaking process.
File Systems
145. What is a file system? Fresher
A file system is the OS component that organises data on a storage device into named files and directories, tracks which blocks belong to which file, records metadata such as size, timestamps and permissions, and manages free space. It turns a flat array of blocks into a namespace people and programs can use. Examples are ext4, XFS, NTFS, APFS and ZFS.
146. What are the common file allocation methods? Fresher
Contiguous allocation stores a file in consecutive blocks: excellent sequential and random read speed, but it suffers external fragmentation and files cannot easily grow. Linked allocation chains blocks with pointers: no fragmentation and easy growth, but random access requires walking the chain and a corrupt pointer loses the tail. Indexed allocation puts all block pointers in an index block, giving direct access without external fragmentation, at the cost of the index block's overhead for small files.
147. What is an inode? 2–5 yrs
An inode is the on-disk structure holding everything about a file except its name and its data: type, permissions, owner, timestamps, link count, size, and the pointers to its data blocks. Directories map names to inode numbers, which is precisely why one file can have several names — hard links — and why renaming does not move data. The number of inodes is fixed at format time on classic Unix file systems, so a partition can run out of inodes while still having free space.
148. How do inodes address large files with a fixed-size structure? 2–5 yrs
An inode holds a handful of direct block pointers for small files, plus a single indirect pointer to a block of pointers, a double indirect pointer to a block of pointer blocks, and a triple indirect pointer. Small files are reached in one step, and the multi-level indirection extends the maximum size to terabytes without enlarging the inode. The cost is extra block reads for offsets deep in a very large file, which is why modern file systems prefer extents.
149. What is the difference between a hard link and a symbolic link? 2–5 yrs
A hard link is another directory entry pointing at the same inode, so both names are equally real, the file's data survives until the link count reaches zero, and links cannot cross file systems or (normally) point at directories. A symbolic link is a small file containing a path, so it can cross file systems and point at directories, but it breaks if the target is moved or deleted — leaving a dangling link.
150. What are the common directory structures? Fresher
A single-level directory has one namespace for all files, so names must be globally unique — unusable beyond a single user. A two-level structure gives each user their own directory. A tree structure allows arbitrary nesting and is what every modern system uses. An acyclic graph adds shared subdirectories through links, which introduces the deletion problem, and a general graph allows cycles, which requires reference counting or garbage collection to reclaim space safely.
151. How does the OS track free space on a disk? 2–5 yrs
The two standard techniques are a bit vector, with one bit per block, which is compact and makes finding contiguous runs a fast word scan but must be kept in memory to be quick; and a linked list of free blocks, which needs no extra space but makes finding contiguous runs slow. Grouping and counting are optimisations on the list, storing runs as an address plus a length. The critical constraint is that the free-space structure and the allocation must never disagree after a crash.
152. What is a journaling file system? 2–5 yrs
A journaling file system writes a description of an intended metadata update to a sequential log and flushes it before applying the change in place. After a crash, recovery replays or discards the journal entries instead of scanning the whole disk, turning a multi-hour fsck into a few seconds. Metadata-only journaling is the common default because full data journaling writes everything twice; the trade-off is that file contents can still be stale or partially written after a crash.
153. What is the file control block or open file table? 2–5 yrs
When a process opens a file the kernel creates an entry describing the open instance — the current offset, the access mode, and a pointer to the in-memory inode — and returns a small integer file descriptor indexing a per-process table. A system-wide table holds the shared open-file entries, which is how two processes reading the same file keep independent offsets, and how a forked child shares an offset with its parent.
154. What is mounting a file system? 2–5 yrs
Mounting attaches the directory tree of a storage device onto a mount point in the existing namespace, so its contents become reachable by ordinary paths. The kernel reads the device's superblock, verifies the file system type and consistency state, and records the mount so path resolution crossing that point redirects into the new file system. Unmounting flushes buffers and marks the file system clean, which is why pulling a drive without unmounting risks corruption.
155. What is the page cache or buffer cache? 2–5 yrs
The page cache holds recently read and written file blocks in otherwise free RAM, so repeated reads are served without touching the disk and writes can be batched and reordered. It is why a second read of the same file is orders of magnitude faster, and why the OS appearing to use all your memory is normal rather than alarming. The trade-off is that buffered writes are not durable until flushed, which is what fsync forces.
156. What is the difference between a soft and a hard file system check? 2–5 yrs
A consistency check verifies that the metadata agrees with itself — that every allocated block belongs to exactly one file, that link counts match the directory entries, that no inode is both free and referenced. On a journaling file system a clean shutdown flag lets the system skip the full scan and simply replay the log, which is the fast path. A full check is only needed when the journal cannot explain the state, such as after hardware corruption.
157. What is a virtual file system layer? Senior
The VFS is an abstraction inside the kernel that defines a common interface — inode, dentry, file and superblock operations — that every concrete file system implements. It lets one set of system calls work identically over ext4, NFS, a FAT-formatted USB stick, and pseudo file systems like /proc. It is the operating system's own illustration of programming to an interface, and it is what makes mounting heterogeneous file systems into one tree possible.
158. What is copy-on-write in a file system such as ZFS or Btrfs? Senior
A copy-on-write file system never overwrites a live block: a modification writes new blocks and then atomically updates the pointers, so the on-disk state is always consistent without a separate journal. This makes snapshots almost free, since a snapshot is just a retained set of old pointers, and enables cheap checksummed integrity. The costs are fragmentation from scattered writes and worse behaviour when the pool nears full, since there is no free space to write the new copy into.
159. What are file permissions and how does the OS enforce them? 2–5 yrs
Unix permissions store read, write and execute bits for owner, group and others in the inode, and the kernel checks them against the process's effective user and group IDs on open, not on every read. Access control lists extend this with per-user entries, and Windows uses ACLs throughout. Because the check happens at open time, an already-open descriptor keeps working after permissions change, which surprises people the first time they see it.
I/O and Disk Scheduling
160. What is the difference between programmed I/O, interrupt-driven I/O, and DMA? 2–5 yrs
Programmed I/O has the CPU poll a status register and move every byte itself, which is simple and wastes the CPU entirely. Interrupt-driven I/O lets the CPU do other work and be notified on completion, but it still copies each unit of data. Direct Memory Access hands the transfer to a DMA controller that moves data straight between the device and memory, interrupting the CPU only once when the whole block is done — which is why it is the only viable option for disk and network throughput.
161. What is the difference between blocking, non-blocking, and asynchronous I/O? 2–5 yrs
A blocking call suspends the process until the operation completes. A non-blocking call returns immediately with whatever is available, possibly nothing, leaving the caller to poll or to use a readiness interface such as epoll. Asynchronous I/O starts the operation and notifies the caller on completion, so the process never waits and never polls. Readiness-based interfaces tell you when you may act; completion-based ones tell you the work is already done.
162. What is buffering, caching, and spooling in I/O? 2–5 yrs
Buffering holds data temporarily to smooth a speed mismatch between producer and consumer, or to assemble a full block before a transfer. Caching keeps a copy of data that has already been fetched so a repeat access avoids the device. Spooling holds a complete job for a device that cannot interleave requests, such as a printer. The key distinction interviewers probe is that a buffer holds the only copy while a cache holds a redundant one.
163. What is disk seek time, rotational latency, and transfer time? 2–5 yrs
Seek time is moving the head to the right track and is the largest component on a mechanical drive, typically several milliseconds. Rotational latency is waiting for the sector to spin under the head, averaging half a revolution — about 4 ms at 7200 rpm. Transfer time is the actual data movement and is comparatively tiny. Disk scheduling algorithms exist almost entirely to reduce total seek time, which is also why they matter far less on SSDs.
164. How does FCFS disk scheduling work? 2–5 yrs
FCFS services disk requests in arrival order. It is trivially fair and never starves anyone, but it makes no attempt to reduce head movement, so a queue that alternates between the inner and outer edges causes wild swings and the worst total seek distance of any policy. It is the baseline the other algorithms are measured against, and it is a reasonable choice only when the queue depth is usually one.
165. How does SSTF disk scheduling work and what is its problem? 2–5 yrs
Shortest Seek Time First always services the pending request closest to the current head position, which substantially cuts average seek time relative to FCFS. Its problem is starvation: a request at the far edge of the disk may wait indefinitely while a stream of requests keeps arriving near the head. It is also not optimal overall, since a locally greedy choice can leave the head badly placed for the rest of the queue.
166. How does the SCAN or elevator algorithm work? 2–5 yrs
SCAN moves the head in one direction servicing every request it passes, then reverses at the end of the disk and sweeps back, like a lift. It bounds waiting time, since any request will be reached within one full sweep, and it avoids SSTF's starvation. Its weakness is uneven service: a request just behind the head waits for a full round trip, while one just ahead is served immediately.
167. How does C-SCAN differ from SCAN? 2–5 yrs
C-SCAN services requests in one direction only; on reaching the end it returns to the start without servicing anything on the way back, then sweeps again. That return trip looks wasteful, but it makes waiting time much more uniform, because every cylinder is visited at a fixed interval instead of being served twice in quick succession at the turning points. LOOK and C-LOOK are the practical refinements that reverse at the last actual request rather than at the physical end of the disk.
168. Do disk scheduling algorithms still matter with SSDs? Senior
Not in the seek-minimising sense: an SSD has no head, so access time is essentially uniform and reordering by block number buys nothing. What matters instead is queue depth and parallelism across channels, merging adjacent requests to reduce command overhead, and avoiding write amplification from the flash translation layer's garbage collection. Linux reflects this with schedulers such as none and mq-deadline for fast devices rather than the classic elevator.
169. What is RAID and what do the common levels give you? Senior
RAID combines several drives into one logical device for performance, redundancy, or both. RAID 0 stripes with no redundancy — fast, but any failure loses everything. RAID 1 mirrors, giving redundancy and fast reads at half the usable capacity. RAID 5 stripes with distributed parity, surviving one failure with one drive of overhead, and RAID 6 adds a second parity for two failures. The classic warning is that RAID is not a backup: it protects against drive failure, not deletion, corruption or ransomware.
170. What is I/O scheduling fairness versus throughput? Senior
Reordering requests to minimise seeks maximises throughput but can leave individual requests waiting far too long, which is fatal for interactive latency. Deadline-style schedulers therefore attach an expiry to each request and break the seek-optimal order when one is about to expire, and fair-queueing schedulers give each process a share of the device. It is the same tension as CPU scheduling: the schedule with the best aggregate number is rarely the one that feels responsive.
Get these answered live in your real interview
NostrobeAI is a real-time AI interview copilot — it hears the question and drafts a strong answer on your screen, invisible on Zoom, Meet, and Teams. One-time pricing, no subscription.
Try NostrobeAI free