Computer Science

NRB Assistant Director (IT) Notes: Operating Systems

Complete Unit 3 notes for Paper I, Section (A) of the Nepal Rastra Bank Assistant Director (IT) exam: all six sub-topics from process management and deadlock to distributed systems, with 15 diagrams, twelve solved numericals and 70 practice MCQs.

By 87 min read

On this page

These are complete study notes for Unit 3, Operating Systems, of Paper I Section (A) in the Nepal Rastra Bank Assistant Director (Information Technology), Officer Third Class, Technical Service open competitive examination. Everything below follows the official syllabus approved on 2080/05/07, sub-topic by sub-topic, from 3.1 right through to 3.6.

Paper I carries 100 marks with a pass mark of 40: 25 multiple-choice questions of 1 mark each in 30 minutes with 0.2 marks deducted for every wrong answer and no calculator, then 9 short questions of 5 marks and 3 long questions of 10 marks in 2 hours 30 minutes. The questions are set in English and your answers must be written in English, so each section here carries an Exam line — a sentence in examination English that you can reproduce as written. The Nepali paragraphs are there to make the idea clear, not to be copied into your answer book.

This is the third unit of four. Unit 1, Computer Architecture and Organization and Microprocessors and Unit 2, Digital Logic Design are already published. Interrupt handling in section 3.5 below continues directly from the interrupt and bus material in Unit 1 — revise the two together, because examiners frequently ask the hardware and the software halves of the same mechanism in one question.

The same syllabus heading appears in the Assistant Director (Cyber Security) advertisement, and Nepal Bank, Rastriya Banijya Bank and Public Service Commission IT papers cover the same ground, so these notes serve several examinations at once.

Operating Systems is the unit where marks are most reliably won, because the numericals are mechanical: scheduling averages, page-replacement traces, disk head movement and Banker’s algorithm come up again and again and the method never changes. Work the twelve solved numericals until you can reproduce them without the solution. Syllabus text covered here, exactly as NRB prints it:

#Syllabus heading
3.1Definition, Development and Functions of Operating System (OS), Functional Architecture of OS, Types of OS, Network and distributed OS
3.2Processes and Threads: Symmetric Multiprocessing, Micro-kernels, Concurrency, Mutual Exclusion and Synchronization, Inter Process Communications, Semaphores. Features of Process Scheduling; List the features of Inter-Process Communication and Deadlock scheduling
3.3Disk Allocation and Scheduling Methods, Basic Memory Management strategies, Virtual Memory Management Techniques, Define a Process and features of the Process Management System
3.4Concepts of Parallel and Distributed Processing, Identify Security Threats to Operating Systems, authentication and access authorization, system flaws and attacks, trusted system
3.5Input Output and Files: I/O devices and its organization, Principles of I/O software and hardware, Disks, Files and directories organization, File System Implementation, Interrupt handling
3.6Distributed Systems: Distributed Message passing, RPC, Client/Server Computing, Cluster computing

3.1 Definition, development and functions of an operating system

What an operating system is

An operating system is the layer of software that sits between the hardware and the user’s programs. It has two jobs that pull in opposite directions. As an extended machine it hides the ugly detail of the hardware and offers programs a clean interface — a program writes to a file, it does not position a disk head. As a resource manager it decides which process gets the CPU, how much memory each one holds, and whose turn it is to use the printer.

अपरेटिङ सिस्टम भनेको हार्डवेयर र प्रयोगकर्ताका कार्यक्रमबीच बस्ने सफ्टवेयर तह हो। यसले एकातिर हार्डवेयरको जटिलता लुकाएर सजिलो इन्टरफेस दिन्छ, अर्कातिर सीमित स्रोत — सीपीयू, मेमोरी, डिस्क — कसलाई कति दिने भनी व्यवस्थापन गर्छ।

Exam line — An operating system is a program that acts as an intermediary between the computer user and the computer hardware, providing an environment in which a user can execute programs conveniently and efficiently, while managing the allocation of processor, memory, storage and I/O resources among competing processes.

Development of operating systems

GenerationPeriodTechnologyOperating system character
First1945–1955Vacuum tubes, plugboardsNo operating system; the programmer operated the machine directly
Second1955–1965Transistors, punched cardsBatch systems; jobs collected on tape and run in sequence by a resident monitor
Third1965–1980Integrated circuitsMultiprogramming, spooling and time-sharing; OS/360, MULTICS, UNIX
Fourth1980–2000LSI / VLSI, microprocessorsPersonal computers, GUIs, network operating systems; MS-DOS, Windows, Linux
Fifth2000 onwardsMulticore, mobile, virtualisationSMP kernels, hypervisors, mobile and embedded OS, cloud and distributed OS

Three ideas drove the whole progression and each is worth naming in an answer. Spooling (Simultaneous Peripheral Operation On-Line) let a slow card reader or printer work at the same time as the CPU by staging data on disk. Multiprogramming kept several jobs in memory so that when one blocked on I/O the CPU switched to another, raising utilisation. Time-sharing extended multiprogramming by switching so rapidly that each interactive user believed they had the machine to themselves.

स्पुलिङले ढिलो उपकरणलाई डिस्कमार्फत छुट्याएर सीपीयूलाई पर्खनबाट जोगायो, मल्टिप्रोग्रामिङले एउटा काम आई/ओमा अड्किँदा अर्को काम चलाएर सीपीयू खाली बस्न दिएन, र टाइम-सेयरिङले यही अदलबदल यति छिटो गर्‍यो कि हरेक प्रयोगकर्तालाई मेसिन आफ्नै जस्तो लाग्यो।

Exam line — Operating systems evolved from serial processing with no resident software, through resident monitors and batch processing, to multiprogrammed batch systems that overlap computation with input–output, and then to time-sharing systems that provide interactive response by rapid context switching among many users.

Functions of an operating system

  1. Process management — creation, scheduling, suspension, termination, and synchronisation of processes.
  2. Memory management — tracking which parts of main memory are in use, allocating and deallocating space, and providing virtual memory.
  3. File management — creating, deleting, reading and writing files and directories, and mapping them onto secondary storage.
  4. Device (I/O) management — device drivers, buffering, caching, spooling and interrupt handling.
  5. Secondary storage management — free-space management, storage allocation and disk scheduling.
  6. Protection and security — authentication, access control, and isolation of one process from another.
  7. Networking — in network and distributed systems, communication between machines.
  8. Command interpretation — a shell or graphical interface through which users issue requests.
  9. Accounting and performance monitoring — recording resource usage per user or job.
  10. Error detection and handling — responding to hardware and software faults.

Exam line — The principal functions of an operating system are process management, main-memory management, file management, input–output and device management, secondary-storage management, protection and security, networking, command interpretation, resource accounting and error handling.

Functional architecture of an operating system

The classical picture is a set of layers, each using only the services of the layer beneath it:

Users and application programsSystem call interface / APIFile system and I/O subsystemMemory manager (paging, virtual memory)Process manager (scheduler, IPC, synchronisation)Device driversHardware abstraction layerHardware: CPU, memory, disks, devicesusermodekernelmode
Figure 1 — Layered functional architecture of an operating system. Everything below the dashed line executes in kernel mode; the system-call interface is the only legitimate crossing point.

Four structural designs appear in examinations and you should be able to contrast them.

StructureIdeaStrengthWeakness
MonolithicWhole OS is one program in one address spaceFast — calls are ordinary procedure callsHard to maintain; one fault can crash the system
LayeredStrict hierarchy of layers, each using the one belowEasy to design, debug and verifyDefining the layers is difficult; crossing layers costs time
MicrokernelKernel keeps only IPC, scheduling and basic memory; the rest runs as user-space serversReliable, extensible, easier to portMessage passing adds overhead
Modular / hybridSmall core kernel with dynamically loadable modulesFlexibility of microkernel with speed of monolithicStill one address space, so a bad module can crash the kernel

मोनोलिथिकमा पूरै ओएस एउटै कार्यक्रम हुन्छ — छिटो तर मर्मत गाह्रो। लेयर्डमा तहगत बनावट हुन्छ। माइक्रोकर्नलमा कर्नलमा थोरै मात्र राखेर बाँकी सेवा प्रयोगकर्ता क्षेत्रमा चलाइन्छ — भरपर्दो तर सन्देश आदानप्रदानको खर्च बढी। आधुनिक लिनक्स र विन्डोज मोड्युलर/हाइब्रिड हुन्।

Exam line — A monolithic kernel places all operating-system services in a single address space executing in kernel mode, whereas a microkernel retains only inter-process communication, basic scheduling and minimal memory management in the kernel and implements file systems, drivers and networking as user-mode server processes.

Dual-mode operation and system calls

The hardware provides a mode bit. In user mode privileged instructions are forbidden; in kernel (supervisor) mode they are permitted. A user program that needs a privileged service executes a system call, which causes a software interrupt (a trap), switches the mode bit to kernel, and transfers control to a fixed entry point in the OS.

System calls fall into six families: process control (fork, exec, wait, exit), file manipulation (open, read, write, close), device manipulation (ioctl, read, write), information maintenance (getpid, time), communication (pipe, shmget, send, recv) and protection (chmod, umask, chown).

Exam line — Dual-mode operation protects the operating system by allowing privileged instructions only when the mode bit indicates kernel mode; a user process obtains privileged services through a system call, which traps into the kernel, validates the request, performs it and returns to user mode.

Types of operating system

TypeDefining propertyExample
BatchJobs grouped and executed without user interactionEarly IBM mainframe monitors
MultiprogrammingSeveral jobs in memory; CPU switches on I/O waitOS/360 MVT
Time-sharing (multitasking)Rapid switching gives each user interactive responseUNIX, Linux
MultiprocessingTwo or more CPUs under one OSLinux SMP, Windows Server
Real-timeCorrectness depends on meeting deadlinesVxWorks, RTLinux, QNX
DistributedMany machines presented as one systemAmoeba, Plan 9
NetworkMachines keep their own OS but share resourcesWindows Server, NetWare
EmbeddedFixed function, limited resourcesEmbedded Linux, FreeRTOS
MobilePower, touch and connectivity awareAndroid, iOS

A hard real-time system guarantees that a deadline is never missed — a missed deadline is a system failure, as in an aircraft control system. A soft real-time system treats a missed deadline as a degradation in quality, as in video playback. This distinction is a favourite one-mark MCQ.

हार्ड रियल-टाइममा समयसीमा नाघ्नु भनेको प्रणाली नै असफल हुनु हो; सफ्ट रियल-टाइममा गुणस्तर मात्र घट्छ।

Exam line — In a hard real-time system a deadline miss constitutes system failure, whereas in a soft real-time system a deadline miss degrades service quality but the system continues to operate correctly.

Network operating systems and distributed operating systems

A network operating system (NOS) runs on each machine independently. The user is aware of the network: to use a remote file you must know which machine holds it and must explicitly connect, log in or mount. A distributed operating system (DOS) makes a collection of independent machines behave as a single machine; the user does not know, and does not need to know, where a process runs or where a file lives. That property is called transparency.

AspectNetwork OSDistributed OS
TransparencyLow — user sees separate machinesHigh — appears as one system
AutonomyEach node fully autonomousNodes cooperate under one global OS
Resource sharingExplicit (remote login, mount)Automatic and transparent
ScalabilityEasy to add a nodeHarder — global state must scale
Fault toleranceA node failure affects only its usersCan mask node failures
CommunicationFile transfer, remote loginMessage passing, RPC
ExampleWindows Server, Novell NetWareAmoeba, Plan 9, LOCUS

The forms of transparency a distributed OS aims at are worth listing: access, location, migration, relocation, replication, concurrency, failure and persistence transparency.

Exam line — A network operating system provides resource sharing among autonomous machines that the user perceives as distinct, whereas a distributed operating system manages a collection of machines as a single coherent system and hides their distribution behind access, location, migration, replication, concurrency and failure transparency.

3.2 Processes, threads, concurrency and synchronization

Defining a process

A process is a program in execution. The program is passive — bytes in a file; the process is active — it has a program counter, registers, a stack, a data section and a heap. Two processes may run the same program and remain entirely separate.

प्रोग्राम भनेको डिस्कमा राखिएको निष्क्रिय फाइल हो; प्रोसेस भनेको चलिरहेको सक्रिय रूप हो, जससँग आफ्नै प्रोग्राम काउन्टर, रजिस्टर, स्ट्याक र मेमोरी हुन्छ।

The memory image of a process has four parts: text (the code), data (global and static variables), heap (memory allocated at run time) and stack (activation records for function calls, growing towards the heap).

Exam line — A process is a program in execution, comprising the program code, its current activity represented by the program counter and processor registers, a stack of temporary data, a data section of global variables and a heap of dynamically allocated memory.

Stackgrows downwardfree spaceHeapgrows upwardData (globals, static)Text (program code)highlowMemory image of one process
Figure 3 — The four parts of a process image. Stack and heap grow towards one another; the space between them is unallocated.

Process states

StateMeaning
NewThe process is being created
ReadyWaiting to be assigned to a processor
RunningInstructions are being executed
Waiting / BlockedWaiting for an event such as I/O completion
TerminatedExecution has finished

Two further states appear in the seven-state model used when swapping is present: ready-suspended and blocked-suspended, which hold processes that have been moved out of main memory to backing store.

The legal transitions are the examinable part:

NewReadyRunningWaitingTerminatedadmitdispatchinterrupt / quantumexitI/O waitI/O doneThere is no transition from Waiting directly to Running.A process whose event completes re-enters Ready and must be dispatched again.
Figure 2 — The five-state process model. The absence of a Waiting-to-Running edge is the single most frequently examined detail in this diagram.

Note carefully that there is no transition from Waiting directly to Running. A process that finishes waiting re-enters the Ready queue and must be dispatched again. Examiners test exactly this.

Exam line — A process moves from new to ready on admission, from ready to running when dispatched by the scheduler, from running to waiting when it requests input–output, from waiting to ready when the event completes, and from running to ready when its time quantum expires or it is preempted.

Process control block

The process control block (PCB) is the kernel data structure that represents a process. It holds the process identifier, the process state, the program counter, CPU registers, scheduling information such as priority, memory-management information such as page-table pointers, accounting information, and the list of open files and I/O devices.

Exam line — A process control block is the data structure in which the operating system stores all information about a process — identifier, state, program counter, register contents, scheduling priority, memory-management data, accounting data and input–output status — so that execution can be suspended and later resumed.

Context switching

A context switch saves the state of the running process into its PCB and loads the state of the next process from its PCB. It is pure overhead: no useful work is done during it. Its cost depends on hardware support, on the number of registers and on whether the TLB and caches must be flushed. Typical cost is a few microseconds.

कन्टेक्स्ट स्विचले चलिरहेको प्रोसेसको अवस्था पीसीबीमा सुरक्षित गरेर अर्को प्रोसेसको अवस्था फर्काउँछ। यो समयमा कुनै उपयोगी काम हुँदैन, त्यसैले यो शुद्ध ओभरहेड हो।

Threads

A thread is a basic unit of CPU utilisation within a process. Threads of one process share the text, data, heap and open files; each has its own program counter, register set and stack.

Shared between threadsPrivate to each thread
Code (text) sectionProgram counter
Data section (globals)Register set
HeapStack
Open files and signalsThread ID

Benefits are responsiveness, resource sharing, economy (creating a thread is far cheaper than creating a process) and scalability on multiprocessors.

User-level threads are managed by a library without kernel knowledge: switching is fast, but a single blocking system call blocks the whole process and the threads cannot run on different CPUs in parallel. Kernel-level threads are scheduled by the kernel: switching is slower, but one thread blocking does not block the others and true parallelism is possible.

The three multithreading models are many-to-one (many user threads onto one kernel thread), one-to-one (each user thread onto a kernel thread, as in Linux and Windows) and many-to-many (a pool of kernel threads multiplexing many user threads).

Exam line — A thread is a lightweight unit of execution that shares the code, data and operating-system resources of its process while maintaining its own program counter, register set and stack; kernel-level threads permit true parallel execution and non-blocking behaviour, whereas user-level threads switch faster but block the entire process on a blocking system call.

Single-threaded processMulti-threaded processCodeDataFilesCodeDataFilesthreadPCregistersstackthreadPCregsstackthreadPCregsstackthreadPCregsstackShared: code, data, heap, open files | Private to each thread: program counter, registers, stack
Figure 4 — What threads share and what they keep private. Creating a thread is cheap precisely because only the right-hand column must be duplicated.

Symmetric multiprocessing

In symmetric multiprocessing (SMP) every processor runs an identical copy of the operating system, all processors are peers, and any processor may execute any process. There is one shared main memory. Contrast this with asymmetric multiprocessing (AMP), where one master processor runs the OS and schedules work for the slaves.

SMPAMP
OS copyOn every processorOnly on the master
Processor roleAll peersMaster–slave
Failure of one CPUSystem continues at reduced capacityMaster failure halts the system
Load balancingNaturalMaster must distribute explicitly
ComplexityHigher — needs locking of shared kernel dataLower

SMP raises two scheduling issues worth naming: processor affinity, keeping a process on the same CPU so that its cache contents stay warm, and load balancing by push or pull migration.

एसएमपीमा सबै प्रोसेसर बराबर हुन्छन् र प्रत्येकमा ओएसको प्रति चल्छ; एएमपीमा एउटा मास्टरले मात्र ओएस चलाएर अरूलाई काम बाँड्छ।

Exam line — In symmetric multiprocessing all processors are functionally identical peers, each executing a copy of the operating system and capable of running any process from a common ready queue, whereas in asymmetric multiprocessing a designated master processor controls the system and allocates work to subordinate processors.

Microkernels

A microkernel keeps only the minimum in kernel mode: inter-process communication, basic scheduling, and low-level address-space management. File systems, device drivers, networking and protection policies move into user-space servers that communicate by message passing.

Advantages: extensibility (add a server without touching the kernel), reliability (a crashed driver does not take the kernel down), portability, and suitability for distributed systems because messages work equally well across a network. The disadvantage is performance — a request that was one procedure call becomes several messages and mode switches.

Exam line — A microkernel architecture minimises the code executing in kernel mode to inter-process communication, basic scheduling and address-space management, relocating file systems, device drivers and networking into user-mode servers, thereby improving reliability and extensibility at the cost of message-passing overhead.

Concurrency and the critical section problem

Concurrency is the interleaving of several processes or threads. When they share data, interleaving can produce a race condition: the result depends on the order in which the operations happen to run. The classic case is two threads executing count++, which compiles to load, increment, store — interleave them and one increment is lost.

A critical section is the part of a program that accesses shared data. Any correct solution must satisfy three requirements:

  1. Mutual exclusion — at most one process is in its critical section at a time.
  2. Progress — if no process is in its critical section, the choice of who enters next cannot be postponed indefinitely, and only processes wanting to enter take part in the decision.
  3. Bounded waiting — there is a limit on how many times other processes may enter after a process has requested entry and before it is granted.

क्रिटिकल सेक्सन भनेको साझा डाटा छुने कोड खण्ड हो। सही समाधानले तीन सर्त पूरा गर्नुपर्छ — म्युचुअल एक्सक्लुजन, प्रोग्रेस र बाउन्डेड वेटिङ।

Exam line — The critical-section problem requires a protocol satisfying mutual exclusion, progress and bounded waiting, so that no two cooperating processes execute simultaneously within the region of code that accesses shared data.

Peterson’s solution

For two processes, with shared boolean flag[2] and int turn:

/* Process i, where j = 1 - i */
flag[i] = true;
turn    = j;
while (flag[j] && turn == j)
    ;                 /* busy wait */
    /* --- critical section --- */
flag[i] = false;
    /* --- remainder section --- */

It satisfies all three requirements. Its weaknesses are that it is limited to two processes, that it busy-waits (wasting CPU in a spin loop), and that it may fail on modern processors that reorder memory operations unless memory barriers are used.

Hardware support for mutual exclusion

The simplest hardware approach is disabling interrupts, which works only on a uniprocessor and is unacceptable in user code. Practical systems use atomic instructions:

boolean TestAndSet(boolean *target) {
    boolean rv = *target;
    *target = true;
    return rv;
}

/* Mutual exclusion with TestAndSet */
while (TestAndSet(&lock))
    ;            /* busy wait */
    /* critical section */
lock = false;

Swap (or compare_and_swap) achieves the same effect. These guarantee mutual exclusion but not bounded waiting unless extra bookkeeping is added, and they still busy-wait — acceptable for very short critical sections on a multiprocessor, where such a lock is called a spinlock.

Semaphores

A semaphore is an integer variable accessed only through two atomic operations, wait (P, from Dutch proberen) and signal (V, verhogen).

wait(S) {
    while (S <= 0)
        ;        /* or block the process */
    S--;
}

signal(S) {
    S++;         /* or wake a blocked process */
}

A binary semaphore (mutex) takes only 0 and 1 and enforces mutual exclusion. A counting semaphore takes any non-negative value and controls access to a resource with several identical instances; initialise it to the number of instances.

In the implementation used in practice, a waiting process is blocked and placed on a queue rather than spinning, and signal wakes one waiting process — this removes busy waiting.

सेमाफोर भनेको केवल दुई अणुक्रिया — wait र signal — मार्फत मात्र पहुँच गरिने पूर्णांक चल हो। बाइनरी सेमाफोरले म्युचुअल एक्सक्लुजन दिन्छ, काउन्टिङ सेमाफोरले सीमित सङ्ख्याका स्रोत व्यवस्थापन गर्छ।

Two dangers must be named in any answer: deadlock, when processes wait on semaphores held by each other, and priority inversion, when a low-priority process holding a semaphore blocks a high-priority one — solved by priority inheritance.

Exam line — A semaphore is a non-negative integer variable accessed only by the indivisible operations wait and signal; a binary semaphore enforces mutual exclusion over a critical section, while a counting semaphore initialised to n controls allocation of n identical instances of a resource.

Classical synchronization problems

Producer–consumer (bounded buffer). Three semaphores: mutex = 1, empty = n, full = 0.

Producer:                    Consumer:
  wait(empty);                 wait(full);
  wait(mutex);                 wait(mutex);
  add item to buffer;          remove item from buffer;
  signal(mutex);               signal(mutex);
  signal(full);                signal(empty);

The order matters. If the producer executed wait(mutex) before wait(empty) on a full buffer, it would hold the mutex while waiting for space and the consumer could never take any — a deadlock. Examiners ask precisely this.

Readers–writers. Many readers may read concurrently; a writer needs exclusive access. The first-readers-writers solution gives readers priority and can starve writers; the second gives writers priority and can starve readers.

Dining philosophers. Five philosophers, five chopsticks, each needs the two adjacent ones. Picking up the left chopstick then the right deadlocks if all five act together. Standard remedies: allow at most four philosophers at the table; pick up both chopsticks only if both are free; or make one philosopher left-handed (asymmetric ordering).

Exam line — The dining-philosophers problem illustrates deadlock arising from circular wait on shared resources; it is resolved by limiting the number of concurrent contenders, by acquiring all resources atomically, or by imposing an asymmetric ordering on resource acquisition.

Monitors

A monitor is a high-level synchronisation construct: a module in which only one process may be active at a time, with condition variables supporting wait and signal. Unlike a semaphore, where a misplaced wait or a forgotten signal breaks the program, the mutual exclusion is supplied by the compiler. Note that a condition-variable signal on an empty queue has no effect, whereas a semaphore signal is remembered in the counter — a frequent MCQ.

Inter-process communication

Processes cooperate for information sharing, computation speed-up, modularity and convenience. Two models exist.

Shared memoryMessage passing
MechanismA region of memory mapped into both address spacessend and receive system calls
SpeedFaster — no kernel involvement after setupSlower — each message is a system call
SynchronisationProgrammer’s responsibilityBuilt into the primitives
Across machinesNoYes
Typical useLarge data, same machineDistributed systems, small messages

Design decisions in message passing: direct or indirect naming (name the process, or use a mailbox or port); synchronous or asynchronous (blocking or non-blocking send/receive); and buffering capacity (zero, bounded, or unbounded).

Practical IPC mechanisms in UNIX are pipes (unnamed, related processes, unidirectional), named pipes or FIFOs (unrelated processes), message queues, shared memory, semaphores and sockets.

Exam line — Inter-process communication is provided either by shared memory, in which cooperating processes map a common region and synchronise access themselves, or by message passing, in which the kernel transfers data between processes through send and receive primitives that may be direct or indirect, blocking or non-blocking, and buffered or unbuffered.

CPU scheduling criteria

CriterionDefinitionWant
CPU utilisationFraction of time the CPU is busyMaximise
ThroughputProcesses completed per unit timeMaximise
Turnaround timeCompletion time − arrival timeMinimise
Waiting timeTurnaround time − burst timeMinimise
Response timeFirst response − arrival timeMinimise

A preemptive scheduler may take the CPU from a running process; a non-preemptive scheduler waits until the process blocks or terminates. The dispatcher performs the actual switch, and dispatch latency is the time it takes.

Scheduling algorithms

AlgorithmPreemptiveAdvantageDisadvantage
FCFSNoSimple, fair in arrival orderConvoy effect — short jobs wait behind one long job
SJFNoProvably minimal average waiting timeBurst length must be predicted; starves long jobs
SRTFYesBetter average waiting time than SJFMore context switches; starvation
PriorityEitherReflects importanceStarvation, cured by ageing
Round robinYesGood response time, fairPerformance depends on quantum; high switch overhead if quantum too small
Multilevel queueEitherSeparates job classesInflexible; low queues may starve
Multilevel feedback queueYesAdapts to behaviour; most generalMany parameters to tune

The quantum rule for round robin is worth memorising: if the quantum is very large, round robin degenerates to FCFS; if it is very small, overhead dominates. A common guideline is that 80 % of CPU bursts should be shorter than the quantum.

राउन्ड रोबिनमा क्वान्टम धेरै ठूलो भए एफसीएफएस जस्तै हुन्छ, धेरै सानो भए कन्टेक्स्ट स्विचकै खर्चले प्रणाली सुस्त हुन्छ।

Exam line — Shortest-job-first scheduling is provably optimal in minimising average waiting time for a given set of processes, but it is not implementable in practice because the length of the next CPU burst is not known and can only be estimated by exponential averaging of previous bursts.

Deadlock

A deadlock is a situation in which every process in a set is waiting for an event that only another process in the same set can cause. Four conditions must hold simultaneously:

  1. Mutual exclusion — at least one resource is non-sharable.
  2. Hold and wait — a process holds one resource while requesting another.
  3. No preemption — a resource is released only voluntarily.
  4. Circular wait — a closed chain of processes each waiting for the next.

डेडलक हुन माथिका चारै सर्त एकैपटक पूरा हुनुपर्छ। कुनै एउटा मात्र तोडे पनि डेडलक रोकिन्छ।

Four strategies deal with it.

StrategyMethodCost
PreventionDeny one of the four conditions structurallyLow resource utilisation
AvoidanceGrant a request only if the state stays safe (Banker’s algorithm)Needs maximum claims in advance
Detection and recoveryLet deadlock happen; find cycles in the wait-for graph; abort or roll backDetection cost plus loss of work
Ignore (ostrich algorithm)Pretend it cannot happen; reboot if it doesUsed by most general-purpose systems

In a resource-allocation graph, a cycle is necessary for deadlock; if every resource type has exactly one instance, a cycle is also sufficient. With multiple instances a cycle merely indicates the possibility.

A safe state is one in which some sequence of all processes can complete, each obtaining its maximum need from available resources plus those held by earlier processes in the sequence. Every safe state is deadlock-free; an unsafe state is not necessarily deadlocked, but may become so.

Exam line — Deadlock requires the simultaneous presence of mutual exclusion, hold and wait, no preemption and circular wait; deadlock avoidance using Banker’s algorithm admits a resource request only when the resulting state is safe, that is, when there exists a sequence in which every process can obtain its maximum demand and terminate.

R1R2R3P1P2P3requestassignedrequestassignedrequestassignedCycle presentP1 -> R2 -> P2 -> R3 -> P3 -> R1 -> P1Single instance per resource type:a cycle is necessary AND sufficient— the system is deadlocked.Multiple instances: a cycle isnecessary but not sufficient.
Figure 7 — A resource-allocation graph containing a cycle. Circles are processes, rectangles resource types, dots instances.

3.3 Memory management, virtual memory and disk scheduling

Basic memory management concepts

A program’s addresses pass through three forms. Compile time binding produces absolute code and requires the load address to be known in advance. Load time binding produces relocatable code bound when the program is loaded. Execution time binding allows the process to move during execution and needs hardware support.

The logical (virtual) address is generated by the CPU; the physical address is seen by the memory unit. The memory management unit (MMU) translates one into the other. In the simplest scheme the MMU is a relocation register added to every logical address, with a limit register checked first to confine the process to its own space.

सीपीयूले बनाउने ठेगाना लजिकल ठेगाना हो, मेमोरीले देख्ने ठेगाना फिजिकल ठेगाना हो, र एमएमयूले एउटालाई अर्कोमा रूपान्तरण गर्छ।

Two further techniques: swapping moves a whole process between main memory and a backing store, and overlays keep only the currently needed part of a program in memory, under programmer control.

Exam line — The memory management unit maps the logical address space generated by the CPU onto physical memory at execution time, checking each address against a limit register so that a process cannot access memory outside its allocated partition.

Contiguous allocation and fragmentation

In fixed (static) partitioning memory is divided in advance into partitions of fixed size, which causes internal fragmentation — memory wasted inside an allocated partition because the process is smaller than it. In variable (dynamic) partitioning partitions are created to fit, which removes internal fragmentation but causes external fragmentation — free memory exists but in scattered pieces too small to use.

FragmentationCauseRemedy
InternalAllocated block larger than requestedSmaller allocation unit
ExternalFree memory split into non-contiguous holesCompaction, or paging / segmentation

Three placement strategies are examined:

  • First fit — allocate the first hole large enough. Fastest.
  • Best fit — allocate the smallest hole large enough. Leaves tiny unusable fragments; requires search.
  • Worst fit — allocate the largest hole. Performs worst in practice.

First fit and best fit both outperform worst fit; first fit is generally fastest and first fit and best fit are comparable in storage utilisation.

Exam line — Internal fragmentation is the unused space within an allocated memory block, whereas external fragmentation is free memory that cannot satisfy a request because it is divided into non-contiguous holes; external fragmentation may be removed by compaction or avoided by non-contiguous allocation schemes such as paging.

Internal fragmentationExternal fragmentationfixed partitions / pagingvariable partitionsprocess 1process 2process 3Red = space wasted inside an allocated blockP1P2P390 units free in total, but in three pieces –a request for 80 units cannot be satisfied.Remedy: compaction, or non-contiguousallocation (paging).
Figure 9 — The two kinds of fragmentation. Internal waste lies inside an allocation; external waste lies between allocations.

Paging

Paging divides the logical address space into fixed-size pages and physical memory into frames of the same size, and allows a process’s pages to be scattered anywhere in memory. This eliminates external fragmentation entirely; the only waste is internal fragmentation in the last page, averaging half a page per process.

A logical address is split into a page number p and a page offset d. For a logical address space of 2^m and page size 2^n, the high-order m−n bits are the page number and the low-order n bits are the offset. The page table maps p to a frame number f, and the physical address is f concatenated with d.

Logical addresspage number poffset dPage table00x0210x1720x0530x0Bindexframe fPhysical addressframe number foffset doffset passes through unchangedTLBchecked first; on a hitthe page table is skipped
Figure 8 — Paging address translation. The offset is copied unchanged; only the page number is translated, which is why page size must be a power of two.

Because the page table itself is in memory, every memory reference would need two accesses. The translation look-aside buffer (TLB), a small associative cache of recent translations, removes most of that cost.

The effective access time with a TLB is

EAT = h x (t_TLB + t_mem) + (1 - h) x (t_TLB + 2 x t_mem)

where h is the TLB hit ratio, t_TLB the TLB lookup time and t_mem the memory access time.

Page tables for large address spaces are themselves large, so systems use hierarchical (multi-level) paging, hashed page tables, or an inverted page table with one entry per physical frame rather than per virtual page.

Protection is provided by bits in each page-table entry: valid/invalid, read/write/execute, and a dirty (modified) bit.

पेजिङले लजिकल ठेगाना क्षेत्रलाई निश्चित आकारका पेजमा र फिजिकल मेमोरीलाई सोही आकारका फ्रेममा बाँड्छ, त्यसैले बाह्य फ्र्यागमेन्टेसन पूरै हट्छ।

Exam line — Paging is a non-contiguous memory-allocation scheme in which logical memory is divided into fixed-size pages and physical memory into frames of identical size, the page table mapping page numbers to frame numbers, thereby eliminating external fragmentation at the cost of a small internal fragmentation in the final page.

Segmentation

Segmentation divides the program according to its logical structure — code, globals, stack, each procedure — into variable-length segments. An address is a pair <segment number, offset>, and the segment table holds a base and a limit for each segment. It matches the programmer’s view and makes sharing and protection natural at the level of a module, but variable-length segments reintroduce external fragmentation.

PagingSegmentation
Block sizeFixedVariable
Divided byHardwareProgrammer’s logical view
FragmentationInternalExternal
AddressOne-dimensionalTwo-dimensional <seg, offset>
Sharing / protectionPer page, less naturalPer segment, natural

Segmented paging combines the two: segments are paged, so the logical structure of segmentation is kept while external fragmentation is removed.

Virtual memory and demand paging

Virtual memory allows a process to execute while only part of it is in main memory. The benefits are that a program may be larger than physical memory, that more processes fit in memory so CPU utilisation and throughput rise, and that less I/O is needed to load or swap a process.

In demand paging a page is brought in only when it is referenced. The valid–invalid bit marks pages not in memory. A reference to such a page causes a page fault, handled as follows:

  1. The hardware traps to the operating system.
  2. The OS checks whether the reference is legal; if not, the process is terminated.
  3. A free frame is found; if none is free, a victim page is chosen by the replacement algorithm and written out if dirty.
  4. The required page is read from backing store into the frame.
  5. The page table and the internal tables are updated, the valid bit is set.
  6. The instruction that caused the fault is restarted.

With page-fault rate p, service time t_f and memory access time t_mem:

EAT = (1 - p) x t_mem + p x t_f

Because t_f is measured in milliseconds and t_mem in nanoseconds, p must be extremely small — this calculation is a standard numerical and is worked below.

Exam line — Demand paging loads a page into memory only when it is referenced; a reference to a page whose valid bit is clear raises a page fault, upon which the operating system locates the page on backing store, selects a victim frame if necessary, performs the transfer, updates the page table and restarts the faulting instruction.

1Reference topage p2Trap to OS:valid bit clear3Locate page onbacking store4Select victim;write backif dirty5Read page in;update tables6Restart theinstructionPage-fault service pathService time is measured in milliseconds against a memory access of nanoseconds,so the fault rate must stay below about one in 400,000 references.
Figure 10 — The six steps of page-fault handling. Note that the instruction is restarted, never resumed mid-way.

Page replacement algorithms

AlgorithmRuleNote
FIFOReplace the oldest pageSimple; suffers Belady’s anomaly
Optimal (OPT / MIN)Replace the page that will not be used for the longest timeLowest possible fault rate; not implementable — needs the future
LRUReplace the least recently used pageGood approximation of optimal; needs counters or a stack
LRU approximationsReference bit, second-chance (clock), enhanced second-chanceCheap in hardware; used in practice
LFU / MFULeast / most frequently usedRarely used; poor performance

Belady’s anomaly is the counter-intuitive result that for some reference strings the number of page faults increases when the number of frames increases. It affects FIFO but not stack algorithms such as LRU and OPT, because in a stack algorithm the set of pages in n frames is always a subset of the set in n+1 frames.

बेलाडी एनोमली भनेको फ्रेमको सङ्ख्या बढाउँदा पनि पेज फल्ट बढ्ने अनौठो अवस्था हो; यो एफआईएफओमा हुन्छ, एलआरयू र अप्टिमलमा हुँदैन।

Exam line — Belady’s anomaly is the phenomenon whereby increasing the number of allocated frames increases the number of page faults for certain reference strings; it occurs in FIFO replacement but cannot occur in stack algorithms such as LRU and optimal replacement.

Frame allocation, thrashing and the working set

Frames may be allocated equally among processes, proportionally to process size, or by priority. Replacement may be local — a process replaces only its own frames — or global — any frame may be taken.

Thrashing occurs when a process spends more time paging than executing, because it does not have enough frames to hold its active pages. The symptom is that CPU utilisation collapses while disk activity saturates; a scheduler that responds by admitting more processes makes it worse.

The locality model explains why: a process moves between localities, and thrashing occurs when the total size of all active localities exceeds physical memory. The working set W(t, Δ) is the set of pages referenced in the last Δ references; if the sum of working-set sizes exceeds the number of frames, a process is suspended. An alternative control is page-fault frequency, which adds frames when the fault rate exceeds an upper bound and removes them below a lower bound.

Exam line — Thrashing is a condition in which a process has insufficient frames to hold its current locality, so that page faults occur continually and the system spends more time in paging than in useful computation; it is controlled by the working-set model or by page-fault-frequency allocation.

Disk structure and allocation methods

A disk address is <cylinder, track, sector>, mapped onto a linear sequence of logical blocks. Access time has three components:

Access time = seek time + rotational latency + transfer time

Average rotational latency is half a revolution. For a disk at r revolutions per minute, average latency in milliseconds is 0.5 x 60000 / r.

Three file-allocation methods on disk:

MethodDescriptionAdvantageDisadvantage
ContiguousFile occupies consecutive blocksExcellent sequential and direct accessExternal fragmentation; file cannot grow easily
LinkedEach block points to the nextNo external fragmentation; file grows freelyDirect access is slow; a lost pointer loses the rest; pointer overhead
IndexedAn index block lists all the file’s blocksDirect access without external fragmentationIndex block overhead, especially for small files

FAT is a variant of linked allocation with all pointers gathered in one table at the start of the volume. UNIX uses an inode with direct blocks plus single, double and triple indirect blocks, giving small files low overhead and large files great capacity.

Free-space management uses a bit vector (one bit per block, easy to find contiguous runs), a linked list of free blocks, grouping, or counting of consecutive free runs.

Disk scheduling

AlgorithmRule
FCFSServe in arrival order; fair but poor
SSTFServe the closest request next; good throughput, may starve distant requests
SCAN (elevator)Head sweeps to one end serving requests, then reverses
C-SCANHead sweeps one way only, then jumps back without serving; more uniform wait
LOOKLike SCAN but reverses at the last request, not the disk end
C-LOOKLike C-SCAN but jumps back from the last request

SSTF is the analogue of SJF and inherits its starvation problem. C-SCAN and C-LOOK give more uniform waiting times than SCAN because the end cylinders are not served twice in quick succession. On modern solid-state drives there is no seek time, so disk scheduling in this sense is largely irrelevant and simple FCFS or fairness-based queueing is used.

एसएसटीएफले सबैभन्दा नजिकको अनुरोध पहिले सेवा गर्छ — थ्रुपुट राम्रो तर टाढाका अनुरोध भोकमरीमा पर्न सक्छन्। स्क्यानले लिफ्टझैँ एक छेउदेखि अर्को छेउसम्म सफाइ गर्छ।

Exam line — Disk scheduling algorithms order pending requests to minimise total head movement; SSTF selects the request with the smallest seek distance and may cause starvation, while SCAN and C-SCAN move the head systematically across the disk and bound the waiting time of every request.

0143753656798122124183199SSTFSCANLOOKTotal head movement — FCFS 640 SSTF 236 SCAN 331 C-SCAN 382 LOOK 299 C-LOOK 322(head starts at cylinder 53 and first moves towards higher cylinder numbers)
Figure 11 — Numerical N9. Head movement under SSTF, SCAN and LOOK for the queue 98, 183, 37, 122, 14, 124, 65, 67 starting at cylinder 53.

Features of the process management system

Collecting the requirements of section 3.3 in the form examiners ask for, a process management system must provide:

  1. Process creation and termination with a parent–child hierarchy.
  2. Process state maintenance through the PCB and the state transition model.
  3. CPU scheduling at long-term, medium-term and short-term levels.
  4. Context switching between processes.
  5. Process synchronisation through semaphores, monitors and locks.
  6. Inter-process communication by shared memory or message passing.
  7. Deadlock handling by prevention, avoidance, detection or recovery.
  8. Memory protection so that one process cannot access another’s space.
  9. Accounting of CPU time, memory and I/O per process.
  10. Signal and exception handling.

The long-term (job) scheduler controls the degree of multiprogramming by admitting jobs; the medium-term scheduler swaps processes out to relieve memory pressure; the short-term (CPU) scheduler chooses which ready process runs next and executes most frequently.

Exam line — The process management subsystem is responsible for process creation and termination, maintenance of process state in the process control block, scheduling at the long-term, medium-term and short-term levels, context switching, synchronisation, inter-process communication, deadlock handling and per-process resource accounting.

3.4 Parallel and distributed processing, and operating system security

Concepts of parallel processing

Parallel processing is the simultaneous execution of instructions by more than one processing element in order to reduce the time to solve a single problem. Flynn’s taxonomy classifies architectures by the multiplicity of instruction and data streams:

ClassInstruction streamsData streamsExample
SISDOneOneClassical uniprocessor
SIMDOneManyVector and array processors, GPUs
MISDManyOneRare; fault-tolerant pipelines
MIMDManyManyMulticore CPUs, clusters, SMP

MIMD divides further into shared-memory multiprocessors (tightly coupled, communicate through memory, limited scalability) and distributed-memory multicomputers (loosely coupled, communicate by messages, scale well).

Speed-up is bounded by Amdahl’s law. If a fraction s of the work is inherently serial and the rest is perfectly parallel across n processors:

Speedup = 1 / ( s + (1 - s) / n )

As n grows without limit the speed-up approaches 1/s. A program that is 10 % serial can never exceed a speed-up of 10, no matter how many processors are supplied — a result worth stating explicitly in an answer.

एम्डालको नियमअनुसार कार्यक्रमको जुन भाग क्रमिक छ, त्यसैले गतिवृद्धिको सीमा तोक्छ। १०% क्रमिक भए जति प्रोसेसर थपे पनि १० गुणाभन्दा बढी छिटो हुँदैन।

Exam line — Amdahl’s law states that the maximum speed-up obtainable by parallel execution is limited by the serial fraction of the computation, approaching the reciprocal of that fraction as the number of processors increases without bound.

Concepts of distributed processing

Distributed processing spreads computation across autonomous machines connected by a network, each with its own memory and clock, communicating only by messages. The motivations are resource sharing, computation speed-up, reliability through replication, and economy — many commodity machines are cheaper than one large one.

The characteristic difficulties are no shared clock (so ordering events needs logical clocks), no shared memory, partial failure (part of the system fails while the rest continues), and network latency and partition. Any honest answer should name partial failure as the distinctive problem: in a single machine, components fail together.

Parallel processingDistributed processing
MemoryUsually sharedPrivate to each node
ClockCommonIndependent
CouplingTightLoose
CommunicationThrough shared memoryBy messages over a network
FailureAll-or-nothingPartial failure is normal
GoalSpeed on one problemSharing, reliability, scale

Security threats to operating systems

Security has three classical goals, the CIA triad: confidentiality (information is disclosed only to authorised parties), integrity (information is modified only in authorised ways) and availability (service is usable when required). Two further goals are commonly added: authenticity and non-repudiation.

Threats are classified by what they attack:

Threat classEffectExample
InterruptionAvailabilityDenial of service, disk destruction
InterceptionConfidentialityWiretapping, illicit copying
ModificationIntegrityAltering a database record
FabricationAuthenticityInserting forged messages

Program threats to name individually:

  • Trojan horse — useful-looking code with a hidden malicious function.
  • Trap door (back door) — a hidden entry point left by a designer.
  • Logic bomb — malicious code triggered by a condition such as a date.
  • Virus — code that attaches to a host program and needs that program to run.
  • Worm — self-contained, self-replicating, spreads over a network without a host.
  • Rootkit — conceals an intruder’s presence by subverting the OS itself.
  • Ransomware — encrypts data and demands payment.
  • Spyware / keylogger — covertly collects information.
  • Botnet — a network of compromised machines under remote command.

The virus–worm distinction is the most common one-mark question: a virus requires a host program and user action; a worm is standalone and self-propagating.

System threats: denial of service, distributed denial of service, port scanning, and privilege escalation.

भाइरसलाई चल्न होस्ट प्रोग्राम र प्रयोगकर्ताको कार्य चाहिन्छ; वर्म आफैँ पूर्ण हुन्छ र सञ्जालमार्फत आफैँ फैलन्छ।

Exam line — A virus is malicious code that attaches itself to a host program and requires execution of that program to propagate, whereas a worm is a self-contained program that replicates and spreads across a network without requiring a host program or user intervention.

Authentication

Authentication establishes who a principal is. The three classical factors are something you know (password, PIN), something you have (smart card, token, OTP device) and something you are (biometric). Using two of different kinds is two-factor authentication.

Passwords are stored not in clear text but as a salted hash. The salt is a random value stored with the hash; it ensures that two users with the same password have different stored hashes and makes precomputed rainbow-table attacks ineffective. A deliberately slow key-derivation function such as bcrypt, scrypt or Argon2 raises the cost of brute force.

Password attacks to name: brute force, dictionary attack, rainbow tables, shoulder surfing, phishing, and credential stuffing.

Exam line — Authentication verifies a claimed identity using knowledge factors, possession factors or inherence factors; operating systems store passwords as salted one-way hashes so that the plaintext cannot be recovered and identical passwords do not produce identical stored values.

Access authorization

Authorisation determines what an authenticated principal may do. The abstract model is the access matrix, with one row per domain (subject) and one column per object, each cell holding the permitted operations. It is too sparse to store directly, so it is implemented in one of two ways:

ImplementationStored asStored withEasy questionHard question
Access control list (ACL)Columns of the matrixEach objectWho may access this file?What may this user access?
Capability listRows of the matrixEach subjectWhat may this user access?Who may access this file?

UNIX uses a compressed ACL: the familiar owner–group–other triple of read, write and execute bits, with setuid, setgid and the sticky bit as extensions.

Role-based access control (RBAC) assigns permissions to roles and roles to users, which scales far better in organisations. Mandatory access control (MAC) enforces a system-wide policy using security labels that users cannot override, in contrast to discretionary access control (DAC) in which the owner of an object sets its permissions.

Two principles must be named: the principle of least privilege — a subject is granted only the rights it needs, for only as long as it needs them — and separation of privilege.

Exam line — The access matrix specifies for every domain and every object the set of permitted operations; it is implemented either as access control lists stored with each object or as capability lists stored with each subject, and the principle of least privilege requires that every subject operate with the minimum rights necessary to complete its task.

System flaws and attacks

  • Buffer overflow — writing past the end of a buffer overwrites the saved return address and redirects execution. Countermeasures: bounds checking, stack canaries, non-executable stack (NX/DEP) and address space layout randomisation (ASLR).
  • Stack smashing and return-oriented programming — chaining existing code fragments to bypass NX.
  • Race condition / TOCTTOU — a check and the subsequent use are not atomic, so the object changes in between; a classic flaw in setuid programs.
  • Privilege escalation — exploiting a flaw to gain rights beyond those assigned; vertical (user to root) or horizontal (one user to another).
  • Injection flaws — unvalidated input interpreted as a command.
  • Covert channel — information leakage through timing or storage not intended as a communication path.
  • Side-channel attack — inferring secrets from power, timing or cache behaviour, as in Spectre and Meltdown.

Exam line — A buffer overflow occurs when a program writes more data into a fixed-length buffer than it can hold, overwriting adjacent memory including the saved return address, which allows an attacker to divert control flow; it is mitigated by bounds checking, stack canaries, non-executable memory and address space layout randomisation.

Trusted systems

A trusted system is one that can be relied upon to enforce a stated security policy. Its core is the trusted computing base (TCB) — the totality of hardware, firmware and software whose correct operation is essential to security. Keeping the TCB small is the design goal, because everything in it must be trusted and verified.

The reference monitor is the abstract mechanism that mediates every access of a subject to an object. It must be complete (impossible to bypass), tamper-proof and small enough to be verified.

Two formal models appear in examinations:

  • Bell–LaPadula protects confidentiality: no read up (simple security property) and no write down (star property).
  • Biba protects integrity and is its dual: no read down and no write up.

The Orange Book (TCSEC) classification, still cited by NRB-style syllabi, grades systems D (minimal), C1 and C2 (discretionary protection), B1, B2 and B3 (mandatory protection with labels) and A1 (verified design).

बेल–लापाडुला मोडेलले गोपनीयता जोगाउँछ — माथिको वर्गीकरण पढ्न नपाइने, तलको वर्गमा लेख्न नपाइने। बिबा मोडेलले अखण्डता जोगाउँछ र ठीक उल्टो नियम लगाउँछ।

Exam line — A trusted system enforces a defined security policy through a reference monitor that is complete, tamper-proof and verifiable, implemented within a trusted computing base comprising all hardware and software upon which security depends; the Bell–LaPadula model preserves confidentiality by prohibiting reads of higher classifications and writes to lower ones.

3.5 Input, output and files

I/O devices and their organization

Devices are classified as block devices (disks, SSDs — addressable in fixed-size blocks, random access) and character devices (keyboards, mice, serial ports, printers — a stream of bytes, no addressing). A third informal class is network devices, which fit neither cleanly and are usually given a socket interface.

Devices differ enormously in data rate, from a keyboard at tens of bytes per second to an NVMe SSD at gigabytes per second — a span of nine orders of magnitude, which is precisely why the I/O subsystem needs buffering and why a single scheduling policy cannot serve all devices.

A device connects to the system through a device controller containing registers that the CPU reads and writes: a status register, a control register, a data-in register and a data-out register. These registers are reached either by port-mapped I/O, using special IN and OUT instructions on a separate address space, or by memory-mapped I/O, in which the registers appear at ordinary memory addresses and are accessed with ordinary load and store instructions.

ब्लक उपकरणले निश्चित आकारका ब्लकमा डाटा दिन्छ र जुनसुकै ठाउँमा पुग्न सकिन्छ; क्यारेक्टर उपकरणले बाइटको धारा दिन्छ। उपकरण नियन्त्रकका रजिस्टरमा पुग्न पोर्ट-म्याप्ड वा मेमोरी-म्याप्ड आई/ओ प्रयोग हुन्छ।

Exam line — Input–output devices are organised as block devices, which transfer fixed-size blocks and support random access, and character devices, which transfer streams of bytes sequentially; each is controlled through a device controller whose status, control and data registers are addressed either by port-mapped or by memory-mapped input–output.

The three techniques of I/O transfer

TechniqueCPU involvementMechanismSuitable for
Programmed I/O (polling)Total — CPU busy-waits on the status bitCPU repeatedly tests the ready flagVery fast devices, or simple embedded systems
Interrupt-driven I/OPer transfer unit — CPU is interrupted when readyDevice raises an interrupt; the handler moves the dataModerate-rate devices
Direct memory access (DMA)Only at start and finishDMA controller transfers a whole block to memory directlyHigh-rate block devices

In DMA the CPU programs the DMA controller with the memory address, the device address, the count and the direction, then continues with other work; the controller raises a single interrupt when the whole block is complete. During the transfer the controller steals bus cycles from the CPU, which is known as cycle stealing.

Exam line — Direct memory access allows a device controller to transfer an entire block of data to or from main memory without CPU intervention, the processor being interrupted only once on completion, which removes the per-byte interrupt overhead of interrupt-driven input–output.

Programmed I/OCPU polls the status bitin a loop until readyCPU busy 100% ofthe transferInterrupt-driven I/ODevice interrupts the CPUwhen it is readyCPU interrupted onceper unit of dataDirect memory accessDMA controller moves thewhole block to memoryCPU interrupted onceper blockThree techniques of input/output transferDMA steals bus cycles from the CPU during the transfer — this is called cycle stealing.
Figure 12 — Programmed, interrupt-driven and DMA transfer, ordered by decreasing CPU involvement.

Interrupt handling

An interrupt is a signal that diverts the processor from its current instruction stream to a handler. The sequence is examinable in order:

  1. The device controller raises the interrupt request line.
  2. The CPU finishes the current instruction and then checks the interrupt line.
  3. The CPU saves the program counter and processor status on the stack.
  4. The CPU determines the interrupt source — by vectored interrupt, where the device supplies an index into the interrupt vector table, or by polling the devices.
  5. Control transfers to the interrupt service routine (ISR).
  6. The ISR saves any further registers it uses, services the device, and clears the interrupt.
  7. The saved state is restored and execution resumes with IRET.

Interrupts are classified as hardware (from devices) and software (traps and system calls), and as maskable (can be disabled) and non-maskable (power failure, memory parity error). Priority among simultaneous interrupts is resolved by daisy chaining or by a priority interrupt controller.

A practical refinement is the split into a top half — a short handler that runs with interrupts disabled and does only what must be immediate — and a bottom half (softirq, tasklet or deferred procedure call) that performs longer processing with interrupts enabled.

इन्टरप्ट आएपछि सीपीयूले चलिरहेको निर्देशन सकेर मात्र प्रतिक्रिया दिन्छ, अवस्था स्ट्याकमा सुरक्षित गर्छ, इन्टरप्ट भेक्टर तालिकाबाट ह्यान्डलरको ठेगाना लिन्छ, सेवा गर्छ, अनि अवस्था फर्काएर अघिको काम जारी राख्छ।

Exam line — On receiving an interrupt the processor completes the current instruction, saves the program counter and status word, obtains the address of the interrupt service routine from the interrupt vector table, executes the routine, and restores the saved state so that the interrupted program resumes transparently.

Interrupt handling sequenceDeviceCPUMemory / ISRraise IRQfinish currentinstructionsave PC + PSWfetch ISR addressfrom vector tableexecute ISR,service devicerestore state,IRETVectored interrupt: the device supplies an index into the interrupt vector table.Polled interrupt: the CPU interrogates each device in turn to find the source.
Figure 13 — The interrupt sequence. The CPU always completes the instruction in progress before acknowledging the request.

Principles of I/O software

I/O software is built in four layers, each with a defined responsibility:

LayerResponsibility
User-level I/O softwareLibrary calls such as printf, spooling daemons
Device-independent OS softwareUniform naming, buffering, caching, error reporting, allocation, block-size independence
Device driversTranslate generic requests into controller register operations
Interrupt handlersWake the driver when the operation completes

The design goals are device independence (a program should work with any device of the right class), uniform naming (a device is named like a file), error handling (handle errors as close to the hardware as possible), synchronous appearance over asynchronous reality (the driver blocks the caller while the transfer proceeds), buffering, and sharable versus dedicated device management.

Three performance techniques must be distinguished, because the examiner will ask for the difference:

  • Buffering — a memory area holding data during transfer, used to cope with speed mismatch, with differing transfer sizes, and to support copy semantics. Single, double and circular buffering.
  • Caching — holding a copy of frequently used data in faster storage. A cache holds a copy; a buffer may hold the only copy.
  • Spooling — holding output for a dedicated device, typically a printer, in a queue on disk so that several processes may “use” the device concurrently.

Exam line — A buffer is a memory region that holds data in transit between two devices or between a device and an application and may contain the only copy of that data, whereas a cache holds a duplicate copy of data whose original resides elsewhere, kept in faster storage to reduce access time.

Files

A file is a named collection of related information recorded on secondary storage, and it is the logical unit of storage presented to the user. Its attributes are name, identifier, type, location, size, protection, and time and ownership information; these are stored in the directory, not in the file itself.

The six basic operations are create, write, read, reposition (seek), delete and truncate. The OS maintains an open-file table, with a per-process table whose entries point into a system-wide table holding the file-control block, the open count and the current file position.

Access methods:

MethodDescription
SequentialRecords processed in order; the commonest
Direct (relative)Any block read or written directly by number
Indexed sequentialAn index maps keys to block numbers, which are then accessed directly

Directory organization

StructurePropertyLimitation
Single-levelOne directory for all usersName collisions; no grouping
Two-levelOne directory per userNo grouping within a user’s files
Tree-structuredArbitrary nesting of subdirectoriesA file has exactly one path
Acyclic graphShared subdirectories and files via linksDeletion and reference counting become tricky
General graphCycles permittedNeeds garbage collection to detect unreachable cycles

A hard link is a second directory entry pointing to the same inode, and the file persists until the reference count reaches zero. A symbolic (soft) link is a file containing a path; deleting the target leaves a dangling link. This distinction is a reliable MCQ.

हार्ड लिङ्कले उही आइनोडलाई अर्को नाम दिन्छ; सिम्बोलिक लिङ्कले बाटो मात्र राख्छ, त्यसैले मूल फाइल मेटिए लिङ्क झुन्डिएको रहन्छ।

File system implementation

The on-disk structures are the boot control block, the volume control block (superblock — block count, free-block count, block size), the directory structure, and the file control block (FCB) or inode for each file. In memory the system keeps a mount table, a directory cache, the system-wide open-file table and buffers.

The virtual file system (VFS) layer gives a uniform interface so that several different file systems — ext4, NTFS, FAT32, NFS — can be used simultaneously through the same system calls.

A UNIX inode holds the attributes and a set of block pointers: typically twelve direct pointers, one single indirect, one double indirect and one triple indirect, so that small files cost nothing extra while very large files remain addressable.

Reliability is provided by consistency checking (fsck, which scans and repairs metadata after a crash — slow on large volumes) and more practically by journaling, in which metadata changes are written first to a log and then applied; after a crash the log is simply replayed. Log-structured file systems extend this idea to all writes.

Exam line — A journaling file system records metadata updates in a sequential log before applying them to the main file-system structures, so that after a system crash recovery consists only of replaying or discarding the log rather than scanning the entire volume for inconsistencies.

inodemode / permissionsowner, groupsize, timestampslink countdirect block 0direct block 1direct block 2… 12 direct pointerssingle indirectdouble indirecttriple indirectdata blockindex blockdata blockdata blockSmall files cost nothing extra; very large files remain addressablethrough one, two or three levels of indirection.
Figure 14 — UNIX inode structure. Direct pointers serve small files; indirect blocks extend the maximum file size without penalising the common case.

3.6 Distributed systems

Definition and goals

A distributed system is a collection of independent computers that appears to its users as a single coherent system. The nodes have no shared memory and no common clock, and coordinate only by exchanging messages.

The goals are resource sharing, computation speed-up, reliability and availability through replication, scalability, and transparency. The obstacles, which an honest answer names alongside the goals, are the absence of a global clock, partial failure, network latency, security over an untrusted network, and the difficulty of maintaining consistency among replicas.

Exam line — A distributed system is a collection of autonomous computers, connected by a network and equipped with distributed system software, which enables the computers to coordinate their activities and to share resources while appearing to users as a single coherent computing facility.

Distributed message passing

Communication rests on send and receive primitives. The design choices are the same as in local IPC but the failure modes are not: a message may be lost, duplicated, reordered or delayed indefinitely, and the sender cannot distinguish a slow receiver from a failed one.

Blocking (synchronous) primitives suspend the sender until the message is received, which is simple to reason about but couples the two processes. Non-blocking (asynchronous) primitives return immediately, which gives concurrency but requires the buffer to remain untouched until the transfer completes.

Reliability is built from acknowledgements, timeouts, sequence numbers for duplicate detection and retransmission. Naming may be direct (process identifier) or indirect (mailbox or port).

Remote procedure call

RPC makes a call to a procedure on another machine look like an ordinary local call. The mechanism:

  1. The client calls a local client stub.
  2. The stub marshals the parameters into a message — converting them to a machine-independent representation such as XDR, which deals with differing word lengths and with big-endian versus little-endian byte order.
  3. The message is sent to the server machine.
  4. The server stub unmarshals the parameters and calls the real procedure.
  5. The result returns by the same route in reverse.

Binding a client to a server is done through a binding service or port mapper. Because messages may be lost or duplicated, RPC defines delivery semantics:

SemanticsGuaranteeImplementation
At most onceNever executed more than once; may not execute at allDuplicate detection with sequence numbers
At least onceExecuted at least once; may repeatRetransmit until acknowledged — safe only for idempotent operations
Exactly onceExecuted precisely onceHardest; needs duplicate filtering plus server-side persistence

The point to make in an answer is that exactly-once semantics cannot be guaranteed in the presence of arbitrary failures, which is why real systems either use at-most-once or design idempotent operations.

आरपीसीले अर्को मेसिनको प्रोसिजरलाई स्थानीय कल जस्तै देखाउँछ। स्टबले प्यारामिटर मार्शल गरेर पठाउँछ। सन्देश हराउन वा दोहोरिन सक्ने भएकाले “एट मोस्ट वन्स”, “एट लिस्ट वन्स” र “एग्ज्याक्ट्ली वन्स” सिमान्टिक्स परिभाषित गरिन्छ।

Exam line — A remote procedure call allows a process to invoke a procedure in a separate address space, usually on another machine, by means of client and server stubs that marshal and unmarshal parameters into machine-independent messages, thereby hiding the communication from the programmer.

Client machineServer machineclient programclient stubtransport / networkserver procedureserver stubtransport / network1 call2 marshal3 request message4 unmarshal5 invoke6 reply messageAt most once | At least once (safe only for idempotent operations) | Exactly onceExactly-once semantics cannot be guaranteed under arbitrary failures.
Figure 15 — Remote procedure call. The stubs hide the network entirely; the delivery semantics are the price of that illusion.

Client/server computing

In the client/server model a server process offers a service and client processes request it. Architectures are classified by how the three logical tiers — presentation, application logic and data — are divided:

ArchitectureDivision
Two-tierClient holds presentation and often logic; server holds data
Three-tierSeparate presentation, application-logic and database tiers
n-tierFurther decomposition, as in modern web and microservice systems

A thin client keeps only presentation locally; a fat client holds substantial application logic. Servers may be stateless (each request self-contained — easy to recover, easy to scale) or stateful (the server remembers the session — more efficient, harder to recover after a crash). The peer-to-peer model is the alternative: every node is both client and server, there is no central point of failure, and discovery is by flooding or a distributed hash table.

Exam line — In the client–server model a server process provides a well-defined service that client processes request over a network; a stateless server retains no information between requests and therefore recovers simply after failure, whereas a stateful server maintains session information and achieves better performance at the cost of more complex recovery.

Cluster computing

A cluster is a group of interconnected whole computers working together as a unified resource, each capable of operating independently. Unlike an SMP machine, the nodes are complete computers; unlike a general distributed system, the nodes are typically homogeneous, co-located and connected by a fast dedicated network.

Cluster typePurposeMechanism
High-availability (failover)Keep a service runningStandby nodes take over on failure; heartbeat monitoring
Load-balancingSpread requestsA dispatcher distributes incoming work
High-performance (HPC)Solve one large problemParallel jobs across nodes, usually with MPI

Clustering methods are passive standby (a backup node idles until the primary fails), active secondary (all nodes work and absorb the load of a failed one), separate servers with data copied between them, shared-nothing with disks partitioned among nodes, and shared-disk with a concurrent file system.

The advantages are absolute scalability (build a cluster far larger than any single machine), incremental scalability (add nodes as demand grows), high availability (the failure of one node need not stop the service) and superior price/performance against a mainframe of equivalent power.

Exam line — A cluster is a group of complete, interconnected computers that cooperate as a single unified computing resource, providing absolute and incremental scalability, high availability through failover of work from a failed node to surviving nodes, and better price-performance than an equivalent single large machine.

Solved numericals

These twelve cover every calculation type the examiner can set from Unit 3. Work them until the method is automatic — in the examination you will not have time to think about procedure, only about arithmetic.

N1. FCFS, SJF and round robin compared

Problem. Four processes arrive together at time 0 with CPU bursts P1 = 6, P2 = 8, P3 = 7, P4 = 3 ms. Compute average waiting and turnaround time under FCFS, SJF, and round robin with quantum 4 ms. Arrival order for FCFS and RR is P1, P2, P3, P4.

FCFS. Completion times 6, 14, 21, 24.

ProcessBurstCompletionTurnaroundWaiting
P16660
P2814146
P37212114
P43242421

Average waiting = (0 + 6 + 14 + 21) / 4 = 10.25 ms; average turnaround = 65 / 4 = 16.25 ms.

SJF. Order of execution P4, P1, P3, P2.

ProcessBurstCompletionTurnaroundWaiting
P43330
P16993
P3716169
P28242416

Average waiting = 28 / 4 = 7.0 ms; average turnaround = 52 / 4 = 13.0 ms.

Round robin, q = 4. Gantt chart:

FCFSP1P2P3P406142124SJFP4P1P3P20391624RR q=4P1P2P3P4P1P2P30481215172124Average waiting time: FCFS 10.25 ms SJF 7.00 ms RR 13.25 ms
Figure 5 — Numerical N1. The same four processes under FCFS, SJF and round robin with a 4 ms quantum. SJF minimises average waiting time; round robin gives the best response time but the worst average.
ProcessBurstCompletionTurnaroundWaiting
P16171711
P28212113
P37242417
P43151512

Average waiting = 53 / 4 = 13.25 ms; average turnaround = 77 / 4 = 19.25 ms.

Conclusion to write. SJF gives the lowest average waiting time, which is the theoretical result; round robin gives the worst average here but the best response time, since every process starts within one quantum cycle.

N2. Shortest remaining time first with staggered arrivals

Problem. P1 arrives at 0 with burst 8, P2 at 1 with burst 4, P3 at 2 with burst 9, P4 at 3 with burst 5. Schedule by SRTF and find the averages.

Trace. At t = 1, P2’s remaining 4 is less than P1’s remaining 7, so P1 is preempted. At t = 2 and t = 3 the arriving processes have larger remaining times than P2’s 3 and 2, so P2 continues to completion at t = 5. The remaining times are then P1 = 7, P3 = 9, P4 = 5, so P4 runs to t = 10, then P1 to t = 17, then P3 to t = 26.

SRTFP1P2P4P1P3015101726P1P2P3P4arrivalsAverage waiting time 6.5 ms average turnaround 13.0 ms
Figure 6 — Numerical N2. Shortest-remaining-time-first preempts P1 at t = 1 when P2 arrives with a shorter remaining burst.
ProcessArrivalBurstCompletionTurnaroundWaiting
P10817179
P214540
P329262415
P4351072

Average turnaround = 52 / 4 = 13.0 ms; average waiting = 26 / 4 = 6.5 ms.

N3. Banker’s algorithm — safe sequence and request grant

Problem. Five processes, three resource types with total instances A = 10, B = 5, C = 7.

ProcessAllocation A B CMax A B C
P00 1 07 5 3
P12 0 03 2 2
P23 0 29 0 2
P32 1 12 2 2
P40 0 24 3 3

Step 1 — Available. Allocated totals are A = 7, B = 2, C = 5, so Available = (10−7, 5−2, 7−5) = (3, 3, 2).

Step 2 — Need = Max − Allocation.

ProcessNeed A B C
P07 4 3
P11 2 2
P26 0 0
P30 1 1
P44 3 1

Step 3 — Safety algorithm. Work = (3, 3, 2).

StepProcessNeed ≤ Work?Work after release
1P1(1,2,2) ≤ (3,3,2) yes(5, 3, 2)
2P3(0,1,1) ≤ (5,3,2) yes(7, 4, 3)
3P4(4,3,1) ≤ (7,4,3) yes(7, 4, 5)
4P0(7,4,3) ≤ (7,4,5) yes(7, 5, 5)
5P2(6,0,0) ≤ (7,5,5) yes(10, 5, 7)

The state is safe, with safe sequence < P1, P3, P4, P0, P2 >.

Step 4 — Request from P1 of (1, 0, 2). Check Request ≤ Need: (1,0,2) ≤ (1,2,2) yes. Check Request ≤ Available: (1,0,2) ≤ (3,3,2) yes. Pretend to allocate: Available becomes (2, 3, 0), P1’s Allocation becomes (3, 0, 2) and its Need becomes (0, 2, 0).

Re-running the safety algorithm from Work = (2, 3, 0): P1 can finish (Need (0,2,0) ≤ (2,3,0)), giving Work = (5, 3, 2), after which P3, P4, P0 and P2 follow exactly as before. The state remains safe, so the request is granted.

N4. Page replacement — FIFO, LRU and optimal

Problem. Reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1 with three frames. Count page faults for FIFO, LRU and optimal replacement.

AlgorithmPage faultsFault rate
FIFO1575 %
LRU1260 %
Optimal945 %

The optimal count is the lower bound that no implementable algorithm can beat; the gap between LRU and optimal is the price of not knowing the future, and the gap between FIFO and LRU is the price of ignoring recency. Always state those two sentences — they turn a numerical into an answer.

N5. Belady’s anomaly demonstrated

Problem. For reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 under FIFO, count faults with 3 frames and with 4 frames.

Three frames.

Ref123412512345
Frame contents11,21,2,34,2,34,1,34,1,25,1,25,1,25,1,25,3,25,3,45,3,4
Fault?FFFFFFFhithitFFhit

Total = 9 faults.

Four frames.

Ref123412512345
Fault?FFFFhithitFFFFFF

Total = 10 faults.

Adding a frame increased the faults from 9 to 10. This is Belady’s anomaly, and it cannot occur under LRU or optimal replacement because those are stack algorithms, in which the set of pages held in n frames is always a subset of the set held in n + 1 frames.

N6. Effective access time with a TLB

Problem. TLB lookup takes 20 ns, main-memory access takes 100 ns, and the TLB hit ratio is 80 %. Find the effective memory access time in a paged system.

On a TLB hit the frame number is known after the TLB lookup, so one memory access follows. On a miss the page table must be read from memory first, then the data — two memory accesses.

EAT = 0.80 x (20 + 100) + 0.20 x (20 + 100 + 100)
    = 0.80 x 120 + 0.20 x 220
    = 96 + 44
    = 140 ns

Without paging the access would be 100 ns, so the overhead is 40 %. Raising the hit ratio to 98 % gives EAT = 0.98 × 120 + 0.02 × 220 = 122 ns, an overhead of only 22 % — which is why TLB hit ratio dominates paging performance.

N7. Effective access time under demand paging

Problem. Memory access time is 200 ns and page-fault service time is 8 ms. (a) Find the effective access time if one access in a thousand faults. (b) Find the maximum acceptable fault rate if the slowdown must be under 10 %.

(a) With p = 0.001 and 8 ms = 8,000,000 ns:

EAT = (1 - 0.001) x 200 + 0.001 x 8,000,000
    = 199.8 + 8,000
    = 8,199.8 ns  (about 8.2 microseconds)

That is a slowdown of roughly 41 times.

(b) A slowdown under 10 % means EAT < 220 ns:

200 + p x (8,000,000 - 200) < 220
p x 7,999,800 < 20
p < 2.5 x 10^-6

Fewer than one fault in 400,000 accesses. This result is the whole argument for why page-fault rates must be kept minute and why thrashing is catastrophic rather than merely slow.

N8. Paging address translation and page-table size

Problem. A system uses 32-bit logical addresses with a 4 KB page size and 4-byte page-table entries. (a) How many bits are the page number and the offset? (b) How large is a single-level page table? (c) Translate logical address 0x00003A7F if page 3 maps to frame 0x0000B.

(a) Page size 4 KB = 2^12, so the offset is 12 bits and the page number is 32 − 12 = 20 bits.

(b) The table has 2^20 = 1,048,576 entries of 4 bytes each = 4 MB per process. This is why single-level tables are abandoned in favour of multi-level, hashed or inverted page tables.

(c) Split 0x00003A7F into the low 12 bits and the rest. The low 12 bits are 0xA7F, the page number is 0x00003 = 3. Page 3 maps to frame 0x0000B, so the physical address is frame × 4096 + offset:

Physical = 0x0000B x 0x1000 + 0xA7F = 0x0000BA7F

N9. Disk scheduling — total head movement

Problem. The request queue is 98, 183, 37, 122, 14, 124, 65, 67. The head is at cylinder 53 and the disk has cylinders 0 to 199. Compute total head movement for FCFS, SSTF, SCAN, C-SCAN, LOOK and C-LOOK, taking the head to be moving towards higher cylinder numbers.

AlgorithmService orderTotal head movement
FCFS98, 183, 37, 122, 14, 124, 65, 6745+85+146+85+108+110+59+2 = 640
SSTF65, 67, 37, 14, 98, 122, 124, 18312+2+30+23+84+24+2+59 = 236
SCAN65, 67, 98, 122, 124, 183, 199, then 37, 14(199−53) + (199−14) = 146 + 185 = 331
C-SCAN65, 67, 98, 122, 124, 183, 199, jump to 0, then 14, 37146 + 199 + 37 = 382
LOOK65, 67, 98, 122, 124, 183, then 37, 14(183−53) + (183−14) = 130 + 169 = 299
C-LOOK65, 67, 98, 122, 124, 183, jump to 14, then 37130 + 169 + 23 = 322

Points to state in the answer. SSTF gives the least movement here but can starve the request at cylinder 183 if nearer requests keep arriving. LOOK improves on SCAN by not travelling to the physical end of the disk. The circular variants move further in total but give far more uniform waiting times, because under SCAN the cylinders near the turning point are served twice in quick succession while the far end waits a full sweep.

N10. Disk access time

Problem. A disk rotates at 7200 rpm, has an average seek time of 9 ms and a transfer rate of 100 MB/s. Find the average time to read one 4 KB block.

Average rotational latency is half a revolution:

One revolution = 60,000 ms / 7200 = 8.33 ms
Average rotational latency = 8.33 / 2 = 4.17 ms
Transfer time = 4,096 bytes / 100 x 10^6 bytes per second = 40.96 microseconds = 0.04 ms
Average access time = 9 + 4.17 + 0.04 = 13.21 ms

Note that seek and rotation account for 99.7 % of the time and the actual data transfer for almost nothing. That single observation justifies disk scheduling, large block sizes, read-ahead and caching, and it is the sentence that earns the mark.

N11. Amdahl’s law

Problem. A program is 25 % inherently serial. Find the speed-up on 8 processors, and the theoretical maximum speed-up.

Speedup(8) = 1 / ( 0.25 + 0.75/8 ) = 1 / ( 0.25 + 0.09375 ) = 1 / 0.34375 = 2.91

Speedup(infinity) = 1 / 0.25 = 4

Eight processors deliver a speed-up of only 2.91, and no number of processors can exceed 4. State the conclusion explicitly: beyond a certain point, adding processors to a program with a fixed serial fraction is wasted expenditure.

N12. Counting semaphore value

Problem. A counting semaphore S is initialised to 3. Seven wait(S) and two signal(S) operations are executed. What is the final value of S and how many processes are blocked?

S_final = 3 - 7 + 2 = -2

In the implementation that allows negative values, S = −2, and the magnitude of the negative value is the number of blocked processes, so two processes are waiting. In the implementation that clamps S at zero, the value is 0 with the same two processes on the semaphore’s queue. Say which convention you are using — examiners accept either, but not an unexplained answer.

Short-answer question bank (5 marks each)

Each of these has appeared, in this or a close form, in NRB, Nepal Bank, RBB or PSC IT papers. The bracketed note is the skeleton that earns full marks in the five or six minutes a 5-mark answer deserves.

  1. Define an operating system and state its functions. (Definition + any six functions, one line each.)
  2. Explain the functional architecture of an operating system with a diagram. (Layer diagram + user/kernel mode boundary + one line per layer.)
  3. Differentiate between a monolithic kernel and a microkernel. (Table of five rows + one example each.)
  4. Distinguish between a network operating system and a distributed operating system. (Table + define transparency.)
  5. What is a real-time operating system? Distinguish hard from soft real-time. (Definition + deadline-miss consequence + one example each.)
  6. Explain dual-mode operation and why it is necessary. (Mode bit, privileged instructions, trap, protection argument.)
  7. What is a system call? Describe its types with examples. (Definition + trap mechanism + six families with one call each.)
  8. Define a process. Draw and explain the process state diagram. (Definition + five states + the six transitions; note waiting never goes directly to running.)
  9. What is a process control block? List its contents. (Definition + eight fields + why it enables context switching.)
  10. Differentiate between a process and a thread. (Table: what is shared, what is private + cost of creation.)
  11. Compare user-level and kernel-level threads. (Table + the blocking-call argument + the parallelism argument.)
  12. Explain the three multithreading models. (Many-to-one, one-to-one, many-to-many with a sketch each.)
  13. What is a context switch? Why is it pure overhead? (Save/restore via PCB + no useful work + factors affecting cost.)
  14. Define symmetric multiprocessing and contrast it with asymmetric multiprocessing. (Table + processor affinity + load balancing.)
  15. State the critical-section problem and its three requirements. (Definition + mutual exclusion, progress, bounded waiting, each explained.)
  16. Explain Peterson’s solution for two processes. (Code + why each of the three requirements holds + the busy-wait limitation.)
  17. What is a semaphore? Differentiate binary from counting semaphores. (Definition + wait/signal code + table + initialisation rule.)
  18. Solve the bounded-buffer problem using semaphores. (Three semaphores, both code blocks, and the deadlock that wrong ordering causes.)
  19. Explain the readers–writers problem and its two variants. (Statement + reader-priority starves writers, writer-priority starves readers.)
  20. Describe the dining-philosophers problem and three solutions. (Statement + deadlock scenario + at-most-four, both-or-neither, asymmetric.)
  21. What is a monitor? How does it differ from a semaphore? (Definition + compiler-enforced mutual exclusion + signal on empty queue is lost.)
  22. Compare shared memory with message passing for IPC. (Table of five rows + when each is appropriate.)
  23. List and explain the criteria used to evaluate CPU scheduling algorithms. (Five criteria with the direction of optimisation.)
  24. Differentiate preemptive from non-preemptive scheduling with examples. (Definition + two algorithms each + the starvation consequence.)
  25. Explain round-robin scheduling and the effect of the time quantum. (Algorithm + large quantum degenerates to FCFS + small quantum means overhead.)
  26. State the four necessary conditions for deadlock. (All four, each with one explanatory line, and the word “simultaneously”.)
  27. Explain the four strategies for handling deadlock. (Prevention, avoidance, detection and recovery, ignore — with the cost of each.)
  28. What is a safe state? Does an unsafe state imply deadlock? (Definition + safe sequence + no: unsafe means deadlock is possible, not certain.)
  29. Differentiate internal from external fragmentation and state the remedies. (Definitions + compaction + paging.)
  30. Compare first fit, best fit and worst fit. (Rule for each + which performs best in practice.)
  31. Explain paging with a diagram of address translation. (Page/frame + address split + page table + TLB + no external fragmentation.)
  32. Compare paging and segmentation. (Table of five rows + segmented paging as the combination.)
  33. What is virtual memory? Explain demand paging and the page-fault sequence. (Definition + benefits + the six-step fault handling + restart the instruction.)
  34. Explain Belady’s anomaly with an example. (Definition + the 9-versus-10 example + stack algorithms are immune.)
  35. What is thrashing? How is it detected and controlled? (Definition + CPU utilisation collapse + working set + page-fault frequency.)
  36. Compare contiguous, linked and indexed file allocation. (Table + one advantage and one disadvantage each.)
  37. Explain any four disk-scheduling algorithms with an example. (FCFS, SSTF, SCAN, C-SCAN with the head movement computed.)
  38. Differentiate programmed I/O, interrupt-driven I/O and DMA. (Table by CPU involvement + cycle stealing.)
  39. Describe the steps in interrupt handling. (The seven-step sequence + vectored versus polled + maskable versus non-maskable.)
  40. Differentiate a buffer from a cache, and explain spooling. (Buffer may hold the only copy, cache holds a duplicate + printer example.)
  41. Explain the directory structures used in file systems. (Five structures + the hard-link versus symbolic-link distinction.)
  42. What is journaling and why is it preferred to consistency checking? (Write-ahead log + replay after crash + fsck is O(volume size).)
  43. Explain remote procedure call and its delivery semantics. (Stub, marshalling, binding + at-most-once, at-least-once, exactly-once + idempotence.)
  44. Differentiate a stateless from a stateful server. (Definition + recovery simplicity versus efficiency.)
  45. What is cluster computing? State its types and advantages. (Definition + HA, load-balancing, HPC + four advantages.)
  46. Define the CIA triad and classify security threats against it. (Three goals + interruption, interception, modification, fabrication.)
  47. Differentiate a virus from a worm, and define a Trojan horse and a logic bomb. (Host requirement versus self-propagation + two definitions.)
  48. Explain the access matrix and its two implementations. (Matrix + ACL stored per object + capability list stored per subject + the two questions each answers.)
  49. What is a buffer overflow? How is it exploited and prevented? (Mechanism + return-address overwrite + canaries, NX, ASLR, bounds checking.)
  50. What is a trusted system? Explain the reference monitor and the Bell–LaPadula model. (TCB + three reference-monitor properties + no read up, no write down.)

Long-answer question bank (10 marks each)

A 10-mark answer needs roughly two pages: a definition, a diagram or table, a worked example, and a closing paragraph of evaluation. Plan the four parts before writing.

  1. Explain the evolution of operating systems from serial processing to modern distributed systems. Five generations in a table; spooling, multiprogramming and time-sharing explained as the three driving ideas; close with multicore and virtualisation.
  2. Describe the structure of an operating system. Compare monolithic, layered, microkernel and modular designs. Layer diagram; comparison table; argue the reliability-versus-performance trade-off; name Linux as modular and MINIX 3 as microkernel.
  3. Explain process management in detail: states, PCB, context switching and the three schedulers. State diagram; PCB contents; context-switch mechanics; long-, medium- and short-term schedulers with their frequencies and purposes.
  4. Discuss the critical-section problem and compare software, hardware and semaphore solutions. Three requirements; Peterson’s code; TestAndSet; semaphore implementation without busy waiting; note priority inversion and its cure.
  5. Explain the producer–consumer, readers–writers and dining-philosophers problems with semaphore solutions. Code for the first; the two variants of the second; the deadlock and three remedies for the third.
  6. Compare CPU scheduling algorithms and compute the averages for a given workload. Table of seven algorithms; then a full Gantt chart and waiting-time computation such as N1 or N2 above; conclude with which criterion each algorithm optimises.
  7. Explain deadlock fully: conditions, resource-allocation graphs, prevention, avoidance by Banker’s algorithm, detection and recovery. All four conditions; cycle is necessary, and sufficient only for single-instance resources; a worked Banker’s example as in N3; recovery by abort or rollback with the victim-selection criteria.
  8. Explain memory-management strategies from contiguous allocation through paging and segmentation to segmented paging. Fragmentation types; placement strategies; paging translation diagram; segmentation table; the combination and why it is used.
  9. Explain virtual memory: demand paging, page replacement algorithms, frame allocation and thrashing. Fault handling; FIFO, LRU, optimal and clock with a worked trace; Belady’s anomaly; the working-set model; the EAT computation of N7 as the justification.
  10. Describe the I/O subsystem: devices, the three transfer techniques, interrupt handling and the layers of I/O software. Device classes; programmed I/O, interrupt-driven I/O and DMA compared; the interrupt sequence; the four software layers; buffering, caching and spooling distinguished.
  11. Explain file-system implementation: allocation methods, directory structures, free-space management and crash recovery. Contiguous, linked and indexed allocation with a table; FAT and inode structures; bit vector and linked list; fsck versus journaling.
  12. Discuss distributed systems: goals, message passing, RPC, client/server models and clusters. Definition and transparency types; the difficulties including partial failure; the RPC mechanism in five steps with delivery semantics; two-tier and three-tier architectures; cluster types and advantages.
  13. Explain operating-system security: threats, authentication, authorisation and trusted systems. CIA triad; the four threat classes; program and system threats; salted password hashing; access matrix with ACL and capabilities; least privilege; TCB, reference monitor and Bell–LaPadula.
  14. Compare parallel and distributed processing, and derive the limit on speed-up. Flynn’s taxonomy; shared-memory versus distributed-memory MIMD; the comparison table; Amdahl’s law derived and applied as in N11; mention Gustafson’s rebuttal for a distinction mark.

70 practice MCQs

Remember the marking: +1 for a correct answer, −0.2 for a wrong one, 0 for blank. Guessing pays only if you can eliminate at least two options.

  1. An operating system acts primarily as — (a) a compiler (b) an interface between the user and the hardware (c) a database manager (d) an input device
  2. Which of the following is NOT a function of an operating system? — (a) memory management (b) process scheduling (c) translating source code into machine code (d) file management
  3. Spooling stands for — (a) Simultaneous Peripheral Operation On-Line (b) System Peripheral Output On-Line (c) Sequential Processing Of On-Line jobs (d) Shared Peripheral Output On-Line
  4. The principal benefit of multiprogramming is — (a) increased CPU utilisation (b) a faster clock (c) more main memory (d) a smaller kernel
  5. The CIA triad in operating-system security stands for — (a) control, integrity, access (b) confidentiality, integrity, availability (c) cryptography, identity, authorisation (d) confidentiality, identity, access
  6. Privileged instructions may be executed only in — (a) user mode (b) kernel mode (c) both modes (d) neither mode
  7. A system call transfers control to the kernel by means of — (a) a page fault (b) a DMA transfer (c) a context switch (d) a trap
  8. A microkernel retains in kernel space — (a) the file system (b) device drivers (c) IPC, basic scheduling and low-level memory management (d) the network stack
  9. An example of a microkernel-based operating system is — (a) MS-DOS (b) MINIX 3 (c) early Linux (d) OS/360
  10. In a hard real-time system a missed deadline constitutes — (a) an acceptable delay (b) a quality degradation (c) a system failure (d) a warning only
  11. The transparency that hides where a file is physically stored is — (a) access transparency (b) location transparency (c) failure transparency (d) concurrency transparency
  12. A worm differs from a virus in that a worm — (a) requires a host program (b) cannot spread over a network (c) is self-contained and self-propagating (d) affects only data files
  13. A process is best defined as — (a) a file stored on disk (b) a compiled binary (c) a program in execution (d) a pool of threads
  14. Which of the following is NOT held in the process control block? — (a) program counter (b) process state (c) CPU register contents (d) the program’s source code
  15. Which state transition is impossible? — (a) running to ready (b) ready to running (c) waiting to running (d) waiting to ready
  16. Threads belonging to the same process share — (a) the stack (b) the register set (c) the code and data sections (d) the program counter
  17. Which of these is private to each thread? — (a) the heap (b) open file descriptors (c) global variables (d) the stack
  18. Mapping many user threads onto a single kernel thread is the — (a) one-to-one model (b) many-to-many model (c) two-level model (d) many-to-one model
  19. In symmetric multiprocessing — (a) every processor runs a copy of the operating system (b) only a master processor runs the operating system (c) there is no shared memory (d) the processors must be heterogeneous
  20. In the Bell–LaPadula model the rules are — (a) no read down and no write up (b) no read up and no write down (c) read and write only within one level (d) no read and no write
  21. A race condition is a situation in which — (a) the outcome depends on the relative order of execution (b) two processes deadlock (c) the CPU remains idle (d) memory is exhausted
  22. Peterson’s solution is designed for — (a) a single process (b) two processes (c) n processes (d) distributed systems
  23. The principal drawback of Peterson’s solution is — (a) it violates mutual exclusion (b) it requires special hardware (c) busy waiting (d) unbounded waiting
  24. TestAndSet is — (a) a system call (b) a semaphore operation (c) a scheduling policy (d) an atomic hardware instruction
  25. The semaphore operation P is equivalent to — (a) wait (b) signal (c) release (d) initialise
  26. An access control list is stored with — (a) each subject (b) the kernel (c) each object (d) the scheduler
  27. To control n identical instances of a resource, a counting semaphore is initialised to — (a) 0 (b) 1 (c) n (d) n − 1
  28. In the bounded-buffer solution with n slots, the semaphore full is initialised to — (a) n (b) 1 (c) 0 (d) n − 1
  29. The dining-philosophers problem chiefly illustrates — (a) starvation alone (b) deadlock and starvation (c) page replacement (d) disk scheduling
  30. In a monitor, mutual exclusion is enforced by — (a) the hardware (b) the compiler and runtime (c) the programmer (d) the scheduler
  31. A capability list is stored with — (a) each object (b) each subject (c) the file system (d) the translation look-aside buffer
  32. An ordinary UNIX pipe is — (a) bidirectional between unrelated processes (b) a shared memory region (c) a network socket (d) unidirectional between related processes
  33. The fastest inter-process communication mechanism on one machine is — (a) a message queue (b) a pipe (c) shared memory (d) a socket
  34. Shortest-job-first scheduling is optimal with respect to — (a) throughput (b) CPU utilisation (c) response time (d) average waiting time
  35. The convoy effect is associated with — (a) FCFS scheduling (b) SJF scheduling (c) round robin (d) priority scheduling
  36. Round robin with a very large time quantum degenerates into — (a) SJF (b) SRTF (c) FCFS (d) priority scheduling
  37. Starvation under priority scheduling is remedied by — (a) preemption (b) a larger quantum (c) swapping (d) ageing
  38. Exactly-once RPC semantics — (a) are trivially achieved (b) cannot be guaranteed under arbitrary failures (c) require no acknowledgements (d) are the default in connectionless protocols
  39. Swapping a process out of main memory is performed by the — (a) long-term scheduler (b) short-term scheduler (c) medium-term scheduler (d) dispatcher
  40. How many conditions must hold simultaneously for deadlock? — (a) two (b) three (c) four (d) five
  41. Circular wait may be prevented by — (a) permitting preemption (b) adding memory (c) using semaphores (d) imposing a total ordering on resource types
  42. Banker’s algorithm performs deadlock — (a) prevention (b) avoidance (c) detection (d) recovery
  43. A state is safe if — (a) no process is waiting (b) all resources are free (c) the resource-allocation graph has no cycle (d) some sequence exists in which every process can obtain its maximum need and terminate
  44. In a resource-allocation graph in which every resource type has exactly one instance, a cycle implies — (a) nothing at all (b) possible deadlock only (c) certain deadlock (d) starvation
  45. A cluster is best described as — (a) a single machine with many cores (b) a group of interconnected complete computers working as one resource (c) a network of dumb terminals (d) a virtual machine monitor
  46. Internal fragmentation is characteristic of — (a) dynamic partitioning (b) segmentation (c) fixed partitioning and paging (d) compaction
  47. External fragmentation may be removed by — (a) using larger pages (b) using smaller processes (c) enlarging the TLB (d) compaction
  48. Paging eliminates — (a) internal fragmentation (b) page faults (c) external fragmentation (d) thrashing
  49. A segmentation address is — (a) one-dimensional (b) two-dimensional (c) three-dimensional (d) always physical
  50. The translation look-aside buffer is — (a) a disk cache (b) a register file (c) part of the page table held in memory (d) a cache of recently used page-table entries
  51. With a page size of 4 KB, the number of offset bits is — (a) ten (b) eleven (c) twelve (d) sixteen
  52. A page fault occurs when — (a) a page is corrupted (b) the page table is full (c) the referenced page is not resident in main memory (d) memory is exhausted
  53. After a page fault has been serviced, the faulting instruction is — (a) skipped (b) aborted (c) queued (d) restarted
  54. Optimal page replacement is not implementable because it requires — (a) additional memory (b) special hardware (c) knowledge of future references (d) a very large TLB
  55. Belady’s anomaly is exhibited by — (a) LRU (b) optimal replacement (c) FIFO (d) the clock algorithm
  56. LRU is immune to Belady’s anomaly because it is a — (a) priority algorithm (b) greedy algorithm (c) circular algorithm (d) stack algorithm
  57. Thrashing is characterised by — (a) high CPU utilisation with little paging (b) high throughput (c) low CPU utilisation with heavy paging (d) low memory usage
  58. The working-set model is used principally to — (a) schedule the CPU (b) allocate disk blocks (c) detect deadlock (d) prevent thrashing
  59. Contiguous file allocation suffers chiefly from — (a) internal fragmentation (b) slow direct access (c) pointer overhead (d) external fragmentation and difficulty of growth
  60. The File Allocation Table is a variant of — (a) contiguous allocation (b) indexed allocation (c) linked allocation (d) hashed allocation
  61. A UNIX inode holds — (a) the file name (b) the directory tree (c) the file’s data blocks themselves (d) the file’s attributes and block pointers
  62. Disk access time is the sum of — (a) seek time and transfer time (b) rotational latency alone (c) seek time, rotational latency and transfer time (d) queueing delay and seek time
  63. Average rotational latency is equal to — (a) one full revolution (b) a quarter of a revolution (c) two revolutions (d) half a revolution
  64. SSTF disk scheduling may cause — (a) deadlock (b) thrashing (c) external fragmentation (d) starvation of distant requests
  65. The elevator algorithm is another name for — (a) FCFS (b) SSTF (c) SCAN (d) C-LOOK
  66. Direct memory access principally reduces — (a) total transfer time only (b) disk seek time (c) memory requirements (d) per-byte CPU involvement
  67. Cycle stealing is associated with — (a) interrupt handling (b) demand paging (c) spooling (d) direct memory access
  68. The interrupt vector table contains — (a) interrupt priorities (b) device status words (c) saved register values (d) the addresses of interrupt service routines
  69. Deleting the target file leaves a dangling reference in the case of a — (a) hard link (b) both link types (c) neither link type (d) symbolic link
  70. In a remote procedure call, packing the parameters into a message is called — (a) binding (b) marshalling (c) spooling (d) buffering

Answer key

1 b2 c3 a4 a5 b6 b7 d8 c9 b10 c
11 b12 c13 c14 d15 c16 c17 d18 d19 a20 b
21 a22 b23 c24 d25 a26 c27 c28 c29 b30 b
31 b32 d33 c34 d35 a36 c37 d38 b39 c40 c
41 d42 b43 d44 c45 b46 c47 d48 c49 b50 d
51 c52 c53 d54 c55 c56 d57 c58 d59 d60 c
61 d62 c63 d64 d65 c66 d67 d68 d69 d70 b

Nepali–English glossary

EnglishनेपालीOne-line meaning
Operating systemसञ्चालन प्रणालीSoftware between hardware and user programs
Kernelकर्नेलThe core of the OS, running in privileged mode
System callसिस्टम कलA user program’s request for an OS service
Processप्रक्रियाA program in execution
Threadथ्रेडA unit of execution inside a process
Process control blockप्रोसेस कन्ट्रोल ब्लकKernel record of everything about a process
Context switchसन्दर्भ परिवर्तनSaving one process’s state and loading another’s
SchedulingतालिकीकरणDeciding which process runs next
Preemptionपूर्वाधिकार हरणTaking the CPU from a running process
StarvationभोकमरीA process never getting the resource it needs
AgeingएजिङRaising priority with waiting time to stop starvation
Concurrencyसहवर्तीपनSeveral activities making progress together
Race conditionरेस कन्डिसनResult depends on execution order
Critical sectionक्रिटिकल सेक्सनCode region that accesses shared data
Mutual exclusionपारस्परिक बहिष्करणOnly one process inside the critical section
SemaphoreसेमाफोरInteger controlled by atomic wait and signal
MonitorमोनिटरConstruct with built-in mutual exclusion
DeadlockडेडलकProcesses each waiting for the others forever
Safe stateसुरक्षित अवस्थाA state from which all processes can finish
Fragmentationखण्डीकरणMemory wasted inside or between allocations
Compactionसङ्कुचनMoving blocks together to merge free space
PagingपेजिङFixed-size blocks of memory, no external fragmentation
Segmentationसेगमेन्टेसनVariable-size logical divisions of a program
Page faultपेज फल्टReference to a page not in main memory
TLBटीएलबीCache of recent page-table entries
Virtual memoryभर्चुअल मेमोरीExecuting a program larger than physical memory
Thrashingथ्र्यासिङMore time spent paging than computing
Working setवर्किङ सेटPages a process has used recently
Belady’s anomalyबेलाडी एनोमलीMore frames causing more page faults
Seek timeसिक टाइमTime to move the head to the right cylinder
Rotational latencyरोटेसनल ल्याटेन्सीTime for the sector to arrive under the head
Disk schedulingडिस्क तालिकीकरणOrdering disk requests to cut head movement
InodeआइनोडStructure holding a file’s attributes and block pointers
Journalingजर्नलिङLogging metadata before applying it, for crash recovery
InterruptअवरोधSignal diverting the CPU to a handler
DMAडीएमएDevice transferring data to memory without the CPU
BufferबफरMemory holding data in transit
Cacheक्यासFast copy of frequently used data
Spoolingस्पुलिङQueueing output on disk for a dedicated device
RPCआरपीसीCalling a procedure on another machine
Marshallingमार्शलिङPacking parameters into a portable message
Stateless serverस्टेटलेस सर्भरServer keeping no session information
Clusterक्लस्टरInterconnected computers acting as one resource
Trusted computing baseविश्वसनीय कम्प्युटिङ आधारAll hardware and software security depends on
Least privilegeन्यूनतम विशेषाधिकारGranting only the rights actually required

Revision checklist

Tick each only when you can do it on blank paper, in English, without notes.

3.1 Fundamentals

  • ☐ Define an operating system in one sentence and list ten functions
  • ☐ Draw the layered functional architecture with the user/kernel boundary
  • ☐ Tabulate the five generations with the technology and OS character of each
  • ☐ Define spooling, multiprogramming and time-sharing and say what problem each solved
  • ☐ Compare monolithic, layered, microkernel and modular structures
  • ☐ Explain dual-mode operation and name the six families of system call
  • ☐ Distinguish hard from soft real-time with an example of each
  • ☐ Tabulate network OS against distributed OS and list the forms of transparency

3.2 Processes and concurrency

  • ☐ Draw the five-state process diagram and justify why waiting cannot go to running
  • ☐ List the contents of a PCB
  • ☐ Tabulate what threads share and what they keep private
  • ☐ Compare user-level and kernel-level threads and name the three models
  • ☐ Define SMP and contrast it with AMP; explain processor affinity
  • ☐ State the three requirements of the critical-section problem
  • ☐ Write Peterson’s solution from memory
  • ☐ Write the semaphore definitions of wait and signal
  • ☐ Solve the bounded-buffer problem and explain the deadlock caused by wrong ordering
  • ☐ State the readers–writers variants and the three dining-philosophers remedies
  • ☐ Compare shared memory with message passing
  • ☐ Tabulate all seven scheduling algorithms with one advantage and one disadvantage
  • ☐ Compute average waiting and turnaround for FCFS, SJF, SRTF and RR
  • ☐ State the four deadlock conditions and the four handling strategies
  • ☐ Run Banker’s algorithm and produce a safe sequence

3.3 Memory and storage

  • ☐ Distinguish internal from external fragmentation and give the remedy for each
  • ☐ Compare first fit, best fit and worst fit
  • ☐ Draw paging address translation and compute page-table size
  • ☐ Compute effective access time with a TLB and under demand paging
  • ☐ Compare paging and segmentation and explain segmented paging
  • ☐ List the six steps of page-fault handling
  • ☐ Trace FIFO, LRU and optimal replacement on a given string
  • ☐ Demonstrate Belady’s anomaly with a worked example
  • ☐ Define thrashing and explain the working-set and page-fault-frequency controls
  • ☐ Compare contiguous, linked and indexed allocation
  • ☐ Compute total head movement for all six disk-scheduling algorithms
  • ☐ List the ten features of a process management system

3.4 Parallel, distributed and security

  • ☐ State Flynn’s taxonomy with an example of each class
  • ☐ Apply Amdahl’s law and state the limiting speed-up
  • ☐ Compare parallel with distributed processing
  • ☐ Define the CIA triad and the four threat classes
  • ☐ Distinguish virus, worm, Trojan horse, logic bomb, rootkit and ransomware
  • ☐ Explain salted password hashing and name four password attacks
  • ☐ Draw the access matrix and compare ACLs with capability lists
  • ☐ Explain buffer overflow and four countermeasures
  • ☐ Define the TCB, the reference monitor and the Bell–LaPadula rules

3.5 Input/output and files

  • ☐ Distinguish block from character devices
  • ☐ Compare programmed I/O, interrupt-driven I/O and DMA
  • ☐ List the seven steps of interrupt handling
  • ☐ Name the four layers of I/O software and their responsibilities
  • ☐ Distinguish buffering, caching and spooling
  • ☐ List file attributes, operations and the three access methods
  • ☐ Compare the five directory structures and distinguish hard from symbolic links
  • ☐ Describe inode structure and explain journaling against fsck

3.6 Distributed systems

  • ☐ Define a distributed system and list its goals and difficulties
  • ☐ Explain message-passing design choices and failure modes
  • ☐ Describe the five steps of RPC and the three delivery semantics
  • ☐ Compare two-tier and three-tier client/server architectures
  • ☐ Distinguish stateless from stateful servers
  • ☐ Name the three cluster types and four advantages of clustering

Frequently asked questions

Which units make up Paper I of the NRB Assistant Director (IT) syllabus?

Section (A) contains four units: Computer Architecture and Organization and Microprocessors, Digital Logic Design, Operating Systems, and Database Management System and Design. Section (B) begins with Computer Networks. Operating Systems is Unit 3, covered in full on this page.

Is a calculator allowed in the NRB IT examination?

No. The objective paper of 25 questions in 30 minutes is written without a calculator, so the scheduling, page-replacement and disk-head calculations must be done mentally or on paper.

How is negative marking applied?

Each correct answer in the objective section earns 1 mark and each wrong answer loses 0.2 marks. A blank earns nothing and loses nothing, so guessing is worth it only when you can eliminate at least two of the four options.

What is the difference between a process and a thread?

A process is a program in execution with its own address space; a thread is a unit of execution inside a process. Threads of one process share the code, data, heap and open files, but each thread has its own program counter, register set and stack. Creating a thread is therefore far cheaper than creating a process.

Why can a process in the waiting state not go directly to running?

When the event a process is waiting for completes, the process becomes eligible to run but the CPU may be occupied by another process. It therefore returns to the ready queue and must be selected again by the short-term scheduler. This transition is a very common examination trap.

What is Belady’s anomaly and which algorithms suffer from it?

Belady’s anomaly is the result that for certain reference strings, increasing the number of allocated frames increases rather than decreases the number of page faults. It affects FIFO replacement. It cannot occur in stack algorithms such as LRU and optimal replacement, because in those the set of pages held in n frames is always a subset of the set held in n + 1 frames.

What is the difference between deadlock prevention and deadlock avoidance?

Prevention structurally denies one of the four necessary conditions, for example by requiring all resources to be requested at once or by imposing a total ordering on resource types. Avoidance permits all four conditions but examines each request before granting it, using advance knowledge of maximum claims to ensure the system stays in a safe state — this is Banker’s algorithm.

Why is SSTF disk scheduling not used in practice despite its low head movement?

SSTF always serves the nearest request, so a request for a distant cylinder can be postponed indefinitely while nearer requests keep arriving. This starvation makes worst-case response time unbounded, which is why SCAN, C-SCAN, LOOK and C-LOOK are preferred. On solid-state drives there is no seek time at all, so the question does not arise.

What is the difference between a virus and a worm?

A virus attaches itself to a host program and requires that program to be executed in order to spread. A worm is a complete, self-contained program that replicates and propagates across a network by itself, requiring neither a host program nor any action by a user.

Can exactly-once semantics be guaranteed in a remote procedure call?

Not under arbitrary failures. If an acknowledgement is lost the client cannot distinguish a failed call from a successful one whose reply went missing. Practical systems therefore implement at-most-once semantics with duplicate detection, or design operations to be idempotent so that at-least-once semantics are safe.

How much of this unit should I expect in the paper?

Each of the four Section (A) units contributes roughly a quarter of the Section (A) questions. Operating Systems reliably yields numerical questions on CPU scheduling, page replacement, disk scheduling and Banker’s algorithm, which are the most predictable marks in the whole paper — the method never changes, only the numbers.