← IB Computer Science

A1.3 · Book pp. 67–102

Operating systems and control systems

Your level

Your computer runs hundreds of processes at once, yet you only ever notice a few. The operating system shares out the hardware so that this feels effortless.

What you need to know

PointTopicLevel
A1.3.1The role of operating systemsSL + HL
A1.3.2The functions of an operating systemSL + HL
A1.3.3Approaches to schedulingSL + HL
A1.3.4Interrupt handling and pollingSL + HL
A1.3.5Managing multitasking and resource allocationHL
A1.3.6Control system componentsHL
A1.3.7Control systems in real-world applicationsHL

🔬 Try this first

Open Task Manager on Windows or Activity Monitor on a Mac. Sort by CPU, then by memory. Count how many processes are running and which ones you did not start yourself.

Next: what an OS does →

A1.3.1 The role of an operating system

An operating system sits between users, applications and hardware. It has two main jobs:

  • Abstraction: it hides hardware detail behind simple services, so an app can save a file without knowing how a disk works.
  • Resource management: it shares out the CPU, memory, storage and devices efficiently and safely.

Common examples are Windows, macOS and Linux on computers, and Android and iOS on phones.

A1.3.2 Functions of an operating system

FunctionWhat the OS does
MemoryGives each process its own protected space and loads programs into RAM. Uses virtual memory on disk when RAM runs out, which is slower.
FilesOrganizes a tree of directories, enforces unique names in a directory, and handles create, read, write, rename, move and delete. Defragmentation rejoins scattered HDD files.
DevicesTalks to hardware through device drivers. Uses buffering, caching and spooling, and Plug and Play to install drivers automatically.
SchedulingDecides which process gets the CPU next.
SecurityUser authentication, permissions, encryption, audit logs and malware protection.
AccountingTracks CPU, memory, disk and network use per process and user for quotas, billing and finding bottlenecks.
GUIWindows, icons, menus and pointers, plus accessibility features, feedback and personalization.
VirtualizationA hypervisor runs several isolated virtual machines on one physical machine. Supports snapshots, live migration and cloud scaling.
NetworkingManages connections, DHCP addresses and protocols such as TCP/IP, HTTP, FTP and SMTP. Provides firewalls and VPNs.

Three I/O techniques

TechniqueIdeaSolves
BufferingHolds data briefly during a transferDifferent speeds at each end
CachingKeeps frequently used data somewhere fastSlow repeated access
SpoolingQueues jobs for a deviceDevices that can only handle one job at a time

Common malware

VirusAttaches to a file and spreads when it runs
WormSpreads across networks by itself
TrojanLooks legitimate but hides harmful code

✍️ Activities

  1. Files: create a ProjectFiles folder with Reports, Data and Images inside. Add text files, then move, rename, delete and restore them. Repeat the tasks in a terminal.
  2. Accessibility: turn on a screen reader and a magnifier, then try using your device.
  3. Compare: install Ubuntu in a virtual machine and compare it with your usual OS for interface, files, memory and updates.
  4. Memory: watch Task Manager while a program opens several large apps. Notice when memory fills up and the system slows down.
Check yourself
  1. Why does each process get its own memory space? So that one process cannot corrupt or read another.
  2. Why is defragmentation not needed for SSDs? They have no moving heads, so scattered blocks do not slow them down the same way.
  3. What does a hypervisor do? It shares hardware between virtual machines and keeps them isolated.

Next: scheduling →

A1.3.3 Approaches to scheduling

The scheduler decides which process runs next. A pre-emptive scheduler can take the CPU away from a running process. A non-pre-emptive one waits for it to stop.

AlgorithmHow it worksPre-emptive?AdvantageDrawback
First come first servedRuns in arrival order until each endsNoSimple, and fair by arrivalConvoy effect: short jobs wait behind long ones
Round robinEach gets a fixed time slice (quantum) in turnYesResponsive, and no process dominatesNeeds a well-chosen quantum: too short wastes time switching, too long behaves like FCFS
PriorityHighest priority runs first. Ties use FCFSCan be eitherCritical tasks run firstStarvation of low priorities, which ageing fixes. Priority inversion
Multilevel queueSeparate queues by process type, each with its own algorithmBetween queues, yesTailored to each type of processComplex. Processes cannot change queue, and low queues may starve

turnaround = finish − arrival   ·   waiting = turnaround − burst

🔬 Lab: scheduling simulator

ProcessArrivalBurstPriority (1 is high)

Worked example: multilevel queue

A system has three queues. Interactive apps use round robin at high priority. Batch jobs use FCFS at medium priority. Background tasks use FCFS at low priority. The scheduler serves the highest queue with work waiting, so background tasks run only while the other two queues are empty. A new interactive task will take over as soon as it arrives.

⚠️ Common mistake

A context switch is not free. The CPU must save one process’s state and restore another, which is why a very short quantum can waste time.

✍️ Programming exercise

Write a simulator for FCFS, then add round robin and compare the average waiting times.

Python FCFS model answer
def fcfs(processes):
    # each process is (name, arrival, burst), sorted by arrival
    clock = 0
    total_wait = total_turn = 0
    for name, arrival, burst in processes:
        clock = max(clock, arrival)     # idle until it arrives
        wait = clock - arrival
        clock += burst
        turn = wait + burst
        total_wait += wait
        total_turn += turn
        print(name, "wait", wait, "turnaround", turn)
    n = len(processes)
    print("average wait", round(total_wait / n, 2))
    print("average turnaround", round(total_turn / n, 2))


fcfs([("P1", 0, 5), ("P2", 2, 3), ("P3", 4, 1), ("P4", 6, 7)])

Next: interrupts and polling →

A1.3.4 Interrupts and polling

Think of a parcel delivery. Polling means you keep walking to the door to check. An interrupt is the doorbell: you carry on working until it rings.

On an interrupt, the CPU saves its state, runs an interrupt service routine (ISR), then restores its state and continues.

CriterionInterruptsPolling
Best eventsInfrequent and unpredictableRegular and predictable
CPU overheadLow, but grows with very frequent interruptsHigh, because it checks even when nothing happened
PowerBetter for batteriesCPU stays active
LatencyFast, but varies under heavy loadPredictable, set by the polling interval
SecurityReacts quickly to critical eventsLong intervals can delay detection
SituationBetter choiceReason
Keyboard and mouse on a laptopInterruptsInput is unpredictable and needs instant feedback
Simple kiosk that is usually idlePollingSimple design, and immediate response is not critical
Video call network trafficInterruptsData needs immediate processing
Remote sensor sending small updatesPollingTraffic is minimal and predictable
Saving a large fileInterruptsThe CPU can do other work until the disk finishes
Airbag collision sensorInterruptsAny delay could be catastrophic
Robot repeating a fixed taskPollingChecks fit a precise, regular timetable
Building temperature sensorPollingTemperature changes slowly

🔬 Lab: the cost of polling

Checks per minute
Checks that found nothing
Average delay in noticing an event

Shorter intervals cut the delay but waste more checks. Interrupts need no checks, though each one still costs a context switch.

⚠️ Common mistake

Neither is simply “better”. Always justify your choice with the context: how often events occur, how predictable they are, the power source and the latency needed.

Check yourself
  1. What is the drawback of very frequent interrupts? Each one costs a context switch, which adds overhead and power use.
  2. Why does battery power favour interrupts? The CPU can stay idle until something happens.

Next: multitasking →

Next: review →

HL A1.3.5 Multitasking and resource allocation

Multitasking switches between tasks so quickly that they seem to run at once. The OS must keep this fair, safe and fast.

ProblemMeaning
Resource contentionProcesses compete for the same CPU, memory or device
StarvationA process is repeatedly denied what it needs
Priority inversionA low-priority process holds something a high-priority one needs
DeadlockProcesses wait for each other in a cycle, so none can continue
Context-switch overheadFrequent switching reduces useful work

Mutual exclusion

Only one process may use a shared resource at a time. Otherwise data can be corrupted.

ToolHow it works
Binary semaphore (mutex)0 or 1. It acts as a lock.
Counting semaphoreCounts free copies of a resource. Wait subtracts 1 and signal adds 1.
LockA process locks a resource before using it. A readers-writer lock allows many readers or one writer.
MonitorA container for shared data and its methods that locks automatically. Condition variables let processes wait for events.

🔬 Lab: counting semaphore with 3 connections

Semaphore value: 3

Click a process to request a connection. Click it again to release.

Handling deadlock

PreventionDesign the system so a deadlock cannot occur
AvoidanceGrant only requests that keep the system safe, as in the Banker’s algorithm
DetectionRegularly check for stuck processes
RecoveryStop a process or reallocate resources to break the cycle
Check yourself
  1. How do starvation and deadlock differ? In starvation, others keep making progress. In deadlock, the waiting processes are all stuck.
  2. Which semaphore suits a pool of five printers? A counting semaphore starting at 5.

Next: control systems →

HL A1.3.6 Control system components

A control system tries to reach a target. The input gives the target, such as a set temperature, and the output is what the system actually does.

Open loopClosed loop
FeedbackNoneMeasures the output and corrects it
Best forSimple, predictable jobsJobs needing accuracy in changing conditions
ExampleA toaster on a timerA thermostat
Set point Controller Actuator Process Sensor measured output feedback
Original diagram of a closed-loop system.
ComponentJobThink of it as
ControllerCompares desired and actual values, then decides what to doBrain
SensorMeasures a physical quantity and produces a signalEyes and ears
ActuatorTurns a command into physical actionMuscles
TransducerConverts one form of energy into another, such as pressure into an electrical signalTranslator
Control algorithmThe rules the controller follows, from simple proportional control to PIDDecision rules

🔬 Lab: open loop against closed loop

Blue line: closed loop, which turns the heater on and off from the sensor. Orange line: open loop, with the heater fixed at half power. It suits only one outdoor temperature. Dashed line: the set point. This is a simplified model.

⚠️ Common mistake

Do not just name the parts. Explain how they work together in a loop: the sensor measures, the controller compares, and the actuator corrects.

Next: real-world uses →

HL A1.3.7 Control systems in use

SystemSensors (input)ControllerActuators (output)
ThermostatTemperature sensorCompares room temperature with the set pointHeater or air conditioner
ElevatorPosition, floor request and door sensorsChooses the next move and when to slow downMotor and door drives
Autonomous vehicleCameras, LiDAR, radar, GPSDecides speed, direction and brakingSteering, throttle and brakes
Washing machineWater level and load sensorsRuns the cycle and adjusts its lengthValves, pump and drum motor
Traffic signalsVehicle and pedestrian detectorsAdjusts the timing of each phaseSignal lights
IrrigationSoil moisture and weather sensorsDecides when and how much to waterPump and valves
Home securityDoor, window and motion sensorsAssesses threats and picks a responseAlarm, door locks and cameras
Automatic doorsInfrared or pressure sensorsDecides when to open and closeDoor motor

Each runs as a loop. In an elevator, position sensors keep updating the controller, which slows the motor so that the car stops exactly at the floor. In an autonomous vehicle, transducers convert sensor data into signals and turn commands into action.

✏️ Book note

The book’s motor exercise reads a potentiometer knob to set speed and calls this feedback. No sensor measures the motor’s actual speed, so that circuit is really open loop. To close the loop, you would add a speed sensor and compare its reading with the target.

✍️ Practical: traffic lights

Build this on an Arduino or in Tinkercad Circuits. Connect red, yellow and green LEDs through 220 Ω resistors to pins 13, 12 and 11.

int red = 13, yellow = 12, green = 11;

void setup() {
  pinMode(red, OUTPUT);
  pinMode(yellow, OUTPUT);
  pinMode(green, OUTPUT);
}

void show(int led, int ms) {
  digitalWrite(led, HIGH);
  delay(ms);
  digitalWrite(led, LOW);
}

void loop() {
  show(green, 5000);
  show(yellow, 2000);
  show(red, 5000);
}

Then add a pushbutton on pin 7 for pedestrians, which makes the system react to an input. Discuss how you could improve it.

Discussion: smart home lighting

Occupancy and light sensors send readings to a controller. It compares them with the time of day and desired brightness, then commands dimmers (actuators). The sensors keep measuring, which closes the loop.

Next: review →

Quick quiz

1. What does abstraction mean for an operating system?
2. Why is virtual memory slower than RAM?
3. Which technique lets several print jobs wait in a queue?
4. What must be installed for an OS to use a new graphics card?
5. Which scheduler is non-pre-emptive?
6. What fixes starvation in priority scheduling?
7. What happens if the round robin quantum is very long?
8. A smartphone needs to save battery while waiting for a touch. Which is better?
9. When can polling beat interrupts?

HL Extra questions

1. A binary semaphore is 0 and Process B needs the resource. What happens?
2. P1 holds file X and wants Y, while P2 holds Y and wants X. What is this?
3. A low-priority process holds a lock that a high-priority process needs. What is this?
4. What does the Banker’s algorithm do?
5. Which system is open loop?
6. Which part turns an electrical signal into movement?

Exam-style questions

These are written for this site in the style of Paper 1. Answer on paper first, then open the mark points.

  1. Describe how an operating system organizes files. [2]

    Mark points
    • Uses a hierarchical tree of directories containing files [1].
    • Enforces rules such as unique names in a directory, and allows operations such as moving and renaming [1].
  2. Outline how an operating system loads an application. [3]

    Mark points
    • Finds the executable on secondary storage [1].
    • Allocates enough memory space for its code and data [1].
    • Copies it into RAM and schedules it to run [1].
  3. Describe memory management in an operating system. [3]

    Mark points
    • Allocates and frees RAM for processes as they need it [1].
    • Keeps each process in its own protected space [1].
    • Uses virtual memory on disk when RAM is full [1].
  4. Outline why an operating system keeps audit logs. [2]

    Mark points
    • Records activity such as logins and file access [1].
    • Lets administrators detect suspicious activity or diagnose problems [1].
  5. Three processes arrive at time 0 in the order A (6 units), B (2), C (1). Calculate the average waiting time under FCFS. [3]

    Mark points
    • A waits 0, B waits 6, C waits 8 [1].
    • 0 + 6 + 8 = 14 [1].
    • 14 ÷ 3 = 4.67 units [1].
  6. Compare first come first served and round robin scheduling. [4]

    Mark points
    • FCFS is simple with low overhead [1], but short tasks can wait behind long ones [1].
    • Round robin is responsive and shares the CPU fairly [1], but context switching adds overhead and it depends on the quantum [1].
  7. Explain how priority scheduling can leave a process waiting indefinitely, and one solution. [3]

    Mark points
    • High-priority processes keep arriving and take the CPU [1].
    • A low-priority process never gets a turn, which is starvation [1].
    • Ageing raises its priority over time until it runs [1].
  8. Discuss whether a hospital heart monitor should use interrupts or polling for a critical alarm sensor. [4]

    Mark points
    • Interrupts respond as soon as the event occurs [1].
    • A critical event is unpredictable and any delay could harm the patient [1].
    • Polling between checks could delay detection [1].
    • Conclusion: interrupts, with the overhead acceptable because alarms are rare [1].

HL Exam-style questions

  1. Explain how a counting semaphore controls access to four licences for a program. [3]

    Mark points
    • Starts at 4, the number of free licences [1].
    • Each process decrements it to take a licence, and waits if it is 0 [1].
    • A process increments it on release, which lets a waiting process continue [1].
  2. Describe how an operating system deals with deadlock. [3]

    Mark points
    • Prevention: design rules so that the cycle cannot form [1].
    • Avoidance: only grant safe requests, such as with the Banker’s algorithm [1].
    • Detection and recovery: find the cycle, then stop a process or reallocate resources [1].
  3. Describe how a greenhouse irrigation system works as a closed-loop control system. [4]

    Mark points
    • A moisture sensor measures the soil and sends a signal to the controller [1].
    • The controller compares the reading with the set point [1].
    • If the soil is too dry, it commands the actuator to open a valve or start a pump [1].
    • The sensor keeps feeding back, so water stops when the target is reached [1].