A Level Computer Science · Chapter 3 · Component 01: Computer systems
The operating system shares a computer's processor, memory and devices between many programs, so that each one runs as if it had the machine to itself.
This chapter teaches what an operating system does and how it manages memory with paging and segmentation. It then teaches how scheduling algorithms share the processor, how interrupts are handled, and how application and utility software differ.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- describe the functions of an operating system and explain why one is needed
- translate a virtual address into a physical address using a page table, and explain paging, segmentation and virtual memory
- count the page faults made by first in, first out and least recently used page replacement
- trace first come first served, shortest job first, shortest remaining time and round robin scheduling, and calculate waiting times
- explain how interrupts are handled, and describe the BIOS, device drivers and virtual machines
- compare distributed, embedded, multi-tasking, multi-user and real-time operating systems
- distinguish applications from utilities, and open source from closed source software
Time: three sessions, about 4 hours, plus the programming task.
You need first: registers, interrupts and the fetch-decode-execute cycle from Processor architecture and performance, and RAM and virtual storage from Types of processor, input, output and storage.
The big picture
The big picture
At any moment your laptop might be playing music, checking for email, downloading a file and showing a web page, while you type in a document. It has only a few processor cores and a fixed amount of memory. Something must decide which program runs when, where each one is kept in memory, and how they share the screen, the keyboard and the disk.
That something is the operating system. It sits between the hardware and every other program. Applications ask the operating system for what they need, such as memory, a file or the network, and the operating system decides how to provide it safely and fairly.
Memory is shared by dividing it into pieces. With paging, memory is split into equal-sized frames and each program into pages of the same size, so a program's pages can sit in any free frames. A page table records where each page is, and every address the program uses is translated on the way to memory.
The processor is shared by scheduling. Programs take turns, each running for a short time before the next gets a go, so quickly that they all seem to run at once. Different scheduling algorithms make different trade-offs between fairness, speed and responsiveness, and their waiting times can be calculated exactly.
Interrupts let the operating system respond to events, such as a key press, a finished disk transfer or a timer running out. The timer interrupt is what lets the scheduler take the processor back from a program that would otherwise never let go.
On top of the operating system sit the programs people use: word processors, browsers, games. Alongside them are utilities, small programs that keep the computer healthy, such as backup and antivirus tools. Some software is open source, with its code published for anyone to read and improve; other software is closed source, its code kept private.
Everything in this chapter is a matter of sharing fairly and safely. Memory, processor time, devices and files are all limited, and every program wants them. The operating system's algorithms decide who gets what, and the calculations in this chapter show what each decision costs.
Section 1
What an operating system does
Functions of an operating system
An operating system, or OS, is the software that manages the computer's hardware and provides services to other programs. Its main jobs are memory management, processor scheduling, handling interrupts, managing files, controlling input and output devices, providing security, and offering a user interface.
The OS hides the details of the hardware. A program that wants to save a file asks the OS to do it, without knowing what kind of disk is fitted or where the free space is. That makes programs simpler to write and lets the same program run on many different machines.
Common mistake: thinking the operating system is the same as an application. An application does a task for the user, such as editing a document. The operating system manages the hardware and provides services that applications rely on. An application cannot run without an operating system beneath it.
Applications reach the operating system through system calls, a fixed set of requests such as "open this file", "give me more memory" or "send this data over the network". Each system call switches the processor into its privileged mode, runs the operating system's code, then switches back. This gate keeps the hardware under the operating system's control.
Protecting programs from each other
Several programs share the same memory and processor, so the OS must stop one from damaging another. Each program is given its own area of memory, and any attempt to reach outside it is blocked. The processor itself has a privileged mode, used only by the OS, so ordinary programs cannot take direct control of the hardware.
Security goes further than memory protection. The operating system keeps user accounts and passwords, controls who may read or change each file, and records important events in logs. Updates to the operating system often fix security holes, which is why installing them promptly matters.
User interfaces
The OS provides a way for people to use the computer. A graphical user interface uses windows, icons, menus and a pointer, and is easy to learn. A command-line interface uses typed commands; it is harder to learn, but fast for experts and easy to automate. Phones use touch interfaces built around gestures.
Worked example 1: who does what
A user saves a document in a word processor. Say which jobs belong to the application and which to the operating system.
| Working | Reason |
|---|---|
| The word processor turns the document into a file format | That is the application's own task |
| It asks the OS to write the file to a named folder | Applications do not control the disk directly |
| The OS finds free space, writes the data and updates the folder | File management is an OS function |
| The OS also checks the user is allowed to write there | Security is an OS function too |
Different devices need different balances of these functions. A phone's operating system puts battery life and touch input first. A server's puts security and many simultaneous users first. A games console's puts graphics performance first. The functions are the same, but their priorities change.
Check yourself. Give two functions of an operating system and explain why each is needed.
Show the answer
Memory management is needed so that several programs can share memory without overwriting each other. Scheduling is needed so that programs take fair turns on the processor and none blocks the others.
Section 2
Paging and segmentation
Paging
With paging, physical memory is divided into fixed-size blocks called frames, and each program is divided into blocks of the same size called pages. Any page can go in any free frame, so a program does not need one continuous block of memory. A page table for each program records which frame holds each page.
Programs use virtual addresses, as if they had memory starting at 0. Each virtual address is split into a page number and an offset within the page. The page table turns the page number into a frame number, and the physical address is the frame's starting address plus the offset.
Derivation: translating a virtual address
With a page size of s bytes, each page covers s consecutive addresses. So the page number is how many whole pages come before the address, and the offset is how far into its page it lies.
The page table gives the frame f that holds this page. Frame f starts at address f × s, and the offset is the same inside the frame as inside the page.
With s = 1,024, virtual address 5,000 is page 4, offset 904. If page 4 is in frame 2, the physical address is 2 × 1,024 + 904 = 2,952.
Figure 3.1 translates any virtual address through a small page table. Move the address and follow the page number, the offset and the frame. Then switch on the wrong model, which adds the offset to the frame number itself.
Translating a virtual address
- Page
- 4
- Offset
- 904
- Physical address
- 2952
Common mistake: adding the offset to the frame number. The frame number counts whole frames, so it must be multiplied by the frame size before the offset is added. Adding the offset to the frame number directly gives an address near the very start of memory, in the wrong frame altogether.
The translation happens on every memory access, so it must be very fast. A part of the processor called the memory management unit does it in hardware. It keeps a small cache of recent translations, so most addresses are translated without even reading the page table.
Worked example 2: translating an address
Pages are 1,024 bytes, and the page table maps page 4 to frame 2. Translate the virtual address 5,000.
| Working | Reason |
|---|---|
| Page = 5000 DIV 1024 = 4 | Four whole pages come before the address |
| Offset = 5000 MOD 1024 = 904 | The address is 904 bytes into page 4 |
| Page 4 is in frame 2, which starts at 2 × 1024 = 2048 | The page table gives the frame |
| Physical address = 2048 + 904 = 2952 | The offset is the same in the frame |
Each entry in a page table holds more than a frame number. A valid bit says whether the page is in RAM at all; if it is not, using the page causes a page fault. Other bits record whether the page may be written, and whether it has changed since it was loaded. That tells the operating system whether it must be saved before being removed.
Worked example 3: wasted space
A program is 10,000 bytes long and pages are 4,096 bytes. How many pages does it need, and how much space is wasted?
| Working | Reason |
|---|---|
| 10,000 ÷ 4,096 is about 2.44 | The program fills two pages and part of a third |
| It needs 3 pages, holding 3 × 4,096 = 12,288 bytes | A part-used page still takes a whole frame |
| Wasted = 12,288 − 10,000 = 2,288 bytes | The unused end of the last page |
| This waste is called internal fragmentation | It is inside the program's own pages |
Paging also protects programs from each other. Each program has its own page table, so its virtual addresses can only ever lead to its own frames. A program cannot even name another program's memory, let alone change it. Pages can also be shared deliberately, such as one copy of a library used by many programs.
Segmentation
Segmentation divides a program into logical parts of different sizes, such as the code, the data and the stack, called segments. Each segment is kept together in memory. Segments match the way programmers think about a program, and each can be given its own protection, such as making the code read-only.
Because segments vary in size, memory can become broken into small gaps between them, too small to use. This is external fragmentation. Paging avoids it, because every frame is the same size; segmentation avoids wasting the end of a page. Many systems combine the two, dividing each segment into pages.
Choosing the page size is a trade-off. Large pages mean smaller page tables and fewer translations, but more waste at the end of each program. Small pages waste less but need larger tables. Most systems use pages of 4 KiB, with larger pages for special uses.
Check yourself. With 1,024-byte pages and page 2 in frame 1, translate the virtual address 3,000.
Show the answer
3000 DIV 1024 = 2, so it is page 2, and 3000 MOD 1024 = 952. Page 2 is in frame 1, which starts at 1,024, so the physical address is 1,024 + 952 = 1,976.
Section 3
Virtual memory and page replacement
Virtual memory
Virtual memory lets a program use more memory than is physically free. Only the pages in use need to be in RAM; the rest wait on the disk. If a program uses a page that is not in RAM, a page fault occurs. The OS pauses the program, loads the page from disk into a free frame, updates the page table and lets the program continue.
Common mistake: thinking a page fault is an error in the program. A page fault is a normal event in virtual memory: the page the program needs is on disk, not in RAM. The OS loads it and the program carries on. Page faults only become a problem when they happen so often that the computer slows down.
Virtual memory lets programs be larger than RAM and lets many programs share it. It also speeds up starting programs, because only the pages needed first are loaded. The rest arrive as they are used, which is called demand paging.
Page replacement
When RAM is full and a new page is needed, the OS must choose a page to remove. First in, first out, or FIFO, removes the page that has been in memory longest. Least recently used, or LRU, removes the page that has gone unused for the longest time. LRU usually makes fewer faults, because pages in recent use are likely to be used again soon.
Page replacement algorithms are compared by counting faults on the same reference string, the list of pages a program uses in order. The ideal algorithm, which nobody can build, would remove the page that will not be needed for the longest time. FIFO and LRU are practical approximations, using the past to guess the future.
Worked example 4: FIFO page replacement
A program uses pages in the order 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, with 3 frames, all empty at the start. Count the page faults with FIFO.
| Working | Reason |
|---|---|
| 7, 0 and 1 are faults that fill the frames; 2 is a fault that removes 7 | The first page in is the first out |
| 0 is a hit; then 3 removes 0, 0 removes 1, 4 removes 2 | FIFO ignores how recently a page was used |
| 2 removes 3, 3 removes 0, 0 removes 4; then 3 and 2 are hits | Keep removing the oldest page |
| 10 faults in total | Count every page that was not already in memory |
Worked example 5: LRU page replacement
Repeat worked example 4 with LRU.
| Working | Reason |
|---|---|
| 7, 0, 1 are faults; 2 removes 7, the least recently used | All four first appearances are faults |
| 0 is a hit; 3 removes 1, because 0 was just used | LRU protects recently used pages |
| 0 hits; 4 removes 2; 2 removes 3; 3 removes 0; 0 removes 4 | Remove whichever page was used longest ago |
| 3 and 2 hit: 9 faults in total | One fewer than FIFO |
Common mistake: thinking more frames always means fewer page faults. With FIFO, adding a frame can occasionally increase the number of faults. The reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 makes 9 faults with 3 frames but 10 with 4. This surprise is called Belady's anomaly.
Real systems approximate LRU, because recording the exact time of every access would be too slow. A common method gives each frame a bit that is set whenever its page is used, and replaces a page whose bit has not been set recently. This keeps most of the benefit of LRU at a fraction of the cost.
Disk thrashing
If a computer runs too many programs for its RAM, pages are constantly removed and needed again soon after. The OS spends most of its time moving pages to and from the disk, and little real work gets done. This is disk thrashing. Adding RAM, or running fewer programs at once, cures it.
The operating system can watch for thrashing by counting page faults. When the rate rises too high, it can suspend some programs, swapping them out entirely so the others have enough frames to run well. The suspended programs resume when memory frees up.
Check yourself. Why does LRU usually make fewer page faults than FIFO?
Show the answer
Programs tend to reuse pages they used recently, such as the code of a loop. LRU keeps those pages and removes the one unused for longest, while FIFO may remove a page that is still in heavy use just because it arrived first.
Section 4
Scheduling
Why scheduling is needed
A processor core runs one program at a time, but a computer has many programs ready to run. The scheduler decides which runs next and for how long. Good scheduling keeps the processor busy, gives each program a fair share, responds quickly to the user, and finishes jobs promptly.
Two measures compare schedules. The turnaround time of a job is the time from its arrival until it finishes. Its waiting time is the time it spends ready but not running, which is the turnaround time minus its burst, the processor time it needs.
Derivation: waiting and turnaround times
A job arrives at time a, needs b units of processor time, and finishes at time f. The time it is in the system from arriving to finishing is its turnaround.
During that time it runs for b units in total, and spends the rest waiting. So the waiting time is the turnaround with the running time taken away.
A job that arrives at 1, needs 4 units and finishes at 12 has a turnaround of 11 and a waiting time of 11 − 4 = 7. Averaging over all jobs compares one algorithm with another.
Common mistake: counting the running time as waiting time. A job's waiting time is only the time it spends ready but not running. Using the finishing time minus the arrival time gives the turnaround time, which includes the time spent running. Subtract the burst to get the waiting time.
A job moves between states as it runs. It is ready when it is waiting for the processor, running when it has it, and blocked when it is waiting for something else, such as a disk read. The scheduler only chooses among ready jobs; blocked jobs rejoin the ready queue when their event happens.
Scheduling can be pre-emptive or non-pre-emptive. A non-pre-emptive scheduler lets a job run until it finishes or blocks. A pre-emptive scheduler can take the processor away, usually when a timer interrupt arrives. Pre-emption is what stops one program from freezing the whole system.
First come, first served
First come, first served, or FCFS, runs jobs to completion in the order they arrive. It is simple and fair in one sense, but a long job at the front makes every short job behind it wait, which gives a high average waiting time.
Gantt charts make scheduling easy to trace. Draw a time line, and shade a block for each job while it runs, labelled with its name. Reading the finishing time of each job straight off the chart, then subtracting its arrival and burst, gives every waiting time with little chance of error.
Worked example 6: first come, first served
Jobs A, B, C and D arrive at times 0, 1, 2 and 3, needing 8, 4, 2 and 6 units. Find each waiting time and the average with FCFS.
| Working | Reason |
|---|---|
| A runs 0–8, B 8–12, C 12–14, D 14–20 | Jobs run to completion in order of arrival |
| Waits: A 0, B 8 − 1 = 7, C 12 − 2 = 10, D 14 − 3 = 11 | Start time minus arrival, as each runs once |
| Average wait = (0 + 7 + 10 + 11) ÷ 4 = 7 | Add the waits and divide by the jobs |
| The short job C waits 10 units for 2 units of work | FCFS punishes short jobs behind long ones |
First come, first served suits batch systems, where jobs are submitted and collected later and nobody is waiting at a screen. It has very little overhead, because the scheduler only has to look at the front of the queue. For interactive use, its long waits make it a poor choice.
Shortest job first and shortest remaining time
Shortest job first, or SJF, runs the shortest waiting job whenever the processor becomes free, but lets each job finish once started. Shortest remaining time, or SRT, goes further: whenever a new job arrives, it can take over if it needs less time than the running job has left. SRT gives the lowest average waiting time, but both need to know each job's length in advance, and long jobs may wait a very long time.
Worked example 7: shortest job first
Use the same four jobs with SJF.
| Working | Reason |
|---|---|
| A runs 0–8, because it is the only job at time 0 | SJF does not stop a running job |
| At 8, C is shortest: C runs 8–10 | Choose the shortest ready job |
| Then B runs 10–14, then D 14–20 | B needs 4 units and D needs 6 |
| Waits: A 0, B 9, C 6, D 11; average 6.5 | Shorter jobs first lower the average |
Worked example 8: shortest remaining time
Use the same four jobs with SRT.
| Working | Reason |
|---|---|
| A runs 0–1; B arrives needing 4, less than A's 7, so B takes over | SRT can pre-empt a running job |
| C arrives at 2 needing 2, less than B's 3: C runs 2–4 | The shortest remaining time always runs |
| B finishes 4–7, D runs 7–13, A finishes 13–20 | A has the most left, so it goes last |
| Waits: A 12, B 2, C 0, D 4; average 4.5 | The lowest average of all, but A waits longest |
Round robin
Round robin gives each job a fixed time slice, called a quantum, in turn. A job that has not finished by the end of its slice goes to the back of the queue. No job can hold the processor for long, so the system stays responsive. That is why most interactive operating systems use round robin, or a variation of it.
Figure 3.2 schedules the same four jobs with each algorithm. Choose an algorithm and, for round robin, a time slice, and compare the average waits. Then switch on the wrong model, which counts running time as waiting.
Scheduling algorithms
- Average waiting time
- 8.75
- Average turnaround
- 13.75
Worked example 9: round robin
Use the same jobs with round robin and a time slice of 3. New arrivals join the queue before a job that has just used its slice.
| Working | Reason |
|---|---|
| A 0–3; B, C and D have arrived, so B 3–6, C 6–8, D 8–11 | Each ready job gets one slice in turn |
| A 11–14, then B 14–15 to finish its 4 units | Jobs that still need time rejoin the queue |
| D 15–18 to finish, then A 18–20 to finish | A needed three slices in all |
| Waits: A 12, B 10, C 4, D 9; average 8.75 | Fair turns, but a higher average wait |
The length of the time slice matters. If it is very long, round robin behaves like first come, first served. If it is very short, the processor spends too much time switching between jobs, saving and restoring registers each time. A slice of around 10 to 100 milliseconds is typical.
Multilevel feedback queues
Real systems often use multilevel feedback queues, which combine these ideas. There are several queues of different priority. New jobs start in the top queue with a short time slice. A job that uses its whole slice moves down to a lower queue with a longer slice. Short, interactive jobs stay near the top and respond quickly, while long jobs sink and run when the processor is free.
Common mistake: thinking round robin always gives the shortest waits. Round robin gives every job a quick turn, which keeps the system responsive, but its average waiting time is often higher than SJF or SRT. It trades efficiency for fairness, as worked example 9 shows.
Starvation is the risk in any priority-based scheme: a low-priority job might never run if higher-priority work keeps arriving. Many schedulers prevent it by ageing, gradually raising the priority of jobs that have waited a long time, so every job eventually gets its turn.
Check yourself. Jobs P, Q and R arrive at 0, 1 and 2, needing 5, 3 and 1 units. Find the average waiting time with FCFS.
Show the answer
P runs 0–5, Q 5–8 and R 8–9. The waits are P 0, Q 5 − 1 = 4 and R 8 − 2 = 6, so the average is 10 ÷ 3, about 3.33 units.
Section 5
Interrupts and system software
Handling an interrupt
At the end of each fetch-decode-execute cycle, the processor checks whether an interrupt is waiting. If one is, and its priority is higher than the current task, the processor saves the contents of its registers, including the program counter, on the stack. It then loads the address of the interrupt service routine, or ISR, into the program counter.
The ISR deals with the event, such as reading the key that was pressed. When it finishes, the saved register values are restored from the stack, and the interrupted program carries on exactly where it stopped, with no idea that anything happened.
Common mistake: thinking an interrupt is handled in the middle of an instruction. The processor checks for interrupts only at the end of each fetch-decode-execute cycle. The current instruction always finishes first, so the program can be resumed cleanly from the next instruction.
Interrupts can interrupt each other. If an interrupt of higher priority arrives while an ISR is running, that ISR's registers are pushed too, and the more urgent ISR runs. The stack lets them unwind in the right order, last in, first out.
Interrupts come from three main sources. Hardware interrupts come from devices, such as a key press or a disk finishing a transfer. Software interrupts come from programs, such as a request to the operating system or an error like dividing by zero. Timer interrupts come from the system clock and drive pre-emptive scheduling.
Worked example 10: the cost of interrupts
A timer interrupt happens every 10 ms, and its ISR, the scheduler, takes 0.2 ms. What fraction of the processor's time goes on handling it?
| Working | Reason |
|---|---|
| In every 10 ms, 0.2 ms is spent in the ISR | One interrupt per period |
| Fraction = 0.2 ÷ 10 = 0.02 | Divide the ISR time by the period |
| That is 2% of the processor's time | Multiply by 100 for a percentage |
| The other 98% is left for programs | A small price for fair scheduling |
The BIOS and booting
When a computer is switched on, RAM is empty. So the processor starts by running a program held in ROM or flash memory, called the BIOS, or its modern replacement, UEFI. It tests the hardware, then finds the operating system on the disk and loads the first part of it, called the bootstrap loader. The loader brings in the rest of the OS.
Firmware updates can replace the BIOS or UEFI code, because it is stored in flash memory rather than true ROM. UEFI also adds secure boot, which checks that the operating system being loaded has a valid digital signature. That stops some kinds of malware from taking control before the operating system starts.
Device drivers and virtual machines
A device driver is a small program that lets the OS control a particular piece of hardware, such as a printer or a graphics card. The OS speaks to every printer in the same way, and the driver translates that into the commands one particular printer understands. New hardware only needs a new driver, not a new OS.
A virtual machine is software that pretends to be a complete computer. One physical computer can run several virtual machines, each with its own operating system, isolated from the others. Virtual machines let a company run many servers on one machine, test software on different systems safely, or run programs written for another platform.
Virtual machines also describe a way of running programs. Java and Python programs can be compiled to an intermediate form called bytecode, which a virtual machine then runs on any computer. The same bytecode works on Windows, macOS and Linux, because each has its own virtual machine to interpret it.
Types of operating system
A multi-tasking OS runs several programs at once by scheduling them. A multi-user OS lets several users share one computer at the same time, each with their own files and permissions, as on a server. A distributed OS spreads the work of one system across many networked computers, which appear to the user as one.
An embedded OS runs inside a dedicated device, such as a washing machine or a car's engine controller. It is small, reliable and designed for one job. A real-time OS guarantees to respond to events within a fixed time, which is essential where a late response is dangerous, such as in aircraft controls or medical equipment.
Many devices combine these types. A phone's operating system is multi-tasking, has real-time parts for handling calls and audio, and is embedded in a single device. A cloud service runs a distributed operating system across many servers, each of which may run many virtual machines.
Check yourself. Why must an aircraft's flight-control computer use a real-time operating system?
Show the answer
The system must respond to sensor readings within a guaranteed time, because a late response could make the aircraft unsafe. A real-time OS guarantees those response times, which an ordinary multi-tasking OS does not.
Section 6
Applications and utilities
Software can be obtained in several ways. It can be bought off the shelf, downloaded from an app store, used through a web browser as a cloud service, or written specially. Each route differs in cost, in how well the software fits the need, and in who is responsible for keeping it working and secure.
Application and utility software
Application software does tasks for the user, such as word processing, spreadsheets, browsing the web, editing photos or playing games. Utility software helps manage and maintain the computer itself. Examples include antivirus software, backup tools, file compression, disk defragmenters and encryption tools.
The distinction is about purpose. A word processor exists to help the user write; an antivirus program exists to protect the computer. Some utilities come with the operating system, while others are installed separately.
A disk defragmenter rearranges the pieces of files on a hard disk so that each file is stored in one continuous run, which makes it faster to read. It is not needed for solid-state drives, which reach every location equally quickly, and defragmenting one only wears it out.
Application software can be general-purpose, such as a word processor sold to millions of users, or bespoke, written for one organisation's exact needs. Bespoke software fits perfectly but is expensive and slow to develop. Off-the-shelf software is cheap and ready at once, but may not do everything the organisation wants.
Open source and closed source software
Open source software is published with its source code, so anyone can read it, change it and share their changes, usually under a licence that keeps those freedoms. Linux, Firefox and Python are open source. Closed source, or proprietary, software keeps its source code private and is sold or licensed for use without the right to change it.
Common mistake: thinking open source means free of any licence. Open source software is released under a licence, which sets the rules for using, changing and sharing it. Some licences require any changed version to be shared as open source too. Open source means the code is open, not that there are no conditions.
Open source software can be checked by anyone, changed to fit a need, and is often free. But support may depend on a community rather than a company, and it can be harder to find help. Closed source software usually comes with professional support and a single responsible company, but users depend on that company and cannot fix problems themselves.
Licences matter for both kinds. A closed source licence usually limits how many computers may run the software and forbids copying or changing it. An open source licence may require that any changed version is also released as open source. Breaking either kind of licence can lead to legal action.
Worked example 11: choosing software
A small charity needs an office suite for 20 computers. One closed source suite costs £60 per computer per year; an open source suite is free. Compare the five-year licence cost and give one other factor.
| Working | Reason |
|---|---|
| Closed source: 20 × £60 = £1,200 per year | One licence for each computer |
| Over five years: 5 × £1,200 = £6,000 | The licence is renewed every year |
| Open source licences cost £0 | The software is free to use and copy |
| Other factors: staff training, file compatibility and support | Cost is only part of the decision |
Many organisations mix the two kinds. They might run an open source operating system on their servers, because it is free and easy to customise. Alongside it they might use a closed source accounting package, which comes with guaranteed support and regular updates for tax rules.
Check yourself. Is a backup program application software or utility software? Explain.
Show the answer
It is utility software. It exists to look after the computer and its data, by keeping copies safe, rather than to carry out a task the user wants for its own sake.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Operating system | Manages hardware and serves programs | Windows, Linux | Memory, scheduling, files, security, interface |
| Paging | Equal-sized pages in any free frames | 1,024-byte pages | page = address DIV s; offset = address MOD s |
| Segmentation | Logical parts of different sizes | Code, data, stack | Can cause external fragmentation |
| Page fault | A needed page is on disk, not in RAM | Load page 4 | Normal; too many cause thrashing |
| FIFO and LRU | Remove the oldest, or least recently used, page | 10 against 9 faults | LRU usually makes fewer faults |
| FCFS and SJF | Arrival order, or shortest job next | Average waits 7 and 6.5 | Waiting = turnaround − burst |
| SRT and round robin | Pre-empt for the shortest; fixed time slices | Averages 4.5 and 8.75 | SRT lowest average; RR most responsive |
| Interrupt | A signal that needs attention | Key press, timer | Registers saved on the stack; ISR runs |
| BIOS, drivers, virtual machines | Start-up program; hardware translators; software computers | Bootstrap loader | Drivers let one OS use any device |
| Open and closed source | Published code, or private code | Linux; proprietary suites | Both come with licences |
Programming task
Programming task: simulating scheduling
Aim
Write a Python program that simulates first come first served and round robin scheduling for a list of jobs, and calculates each job's waiting time and the average. The results must match the worked examples in this chapter.
Design
Each job is a tuple of name, arrival time and burst. The FCFS function sorts by arrival and runs each job to completion, waiting if the processor is idle. The round robin function keeps a queue, admits jobs as they arrive, and gives each a slice of at most the quantum.
Both functions record when each job finishes, then work out each waiting time as the finish time minus the arrival time minus the burst. Keeping that one formula in a shared function means both algorithms are measured the same way.
Code
from collections import deque
def waits(jobs, finish):
return {name: finish[name] - arrival - burst for name, arrival, burst in jobs}
def fcfs(jobs):
time, finish = 0, {}
for name, arrival, burst in sorted(jobs, key=lambda j: j[1]):
time = max(time, arrival) + burst
finish[name] = time
return waits(jobs, finish)
def round_robin(jobs, quantum):
pending = sorted(jobs, key=lambda j: j[1])
remaining = {name: burst for name, _, burst in jobs}
queue, time, finish, i = deque(), 0, {}, 0
while queue or i < len(pending):
while i < len(pending) and pending[i][1] <= time:
queue.append(pending[i][0]); i += 1
if not queue:
time = pending[i][1]; continue
name = queue.popleft()
run = min(quantum, remaining[name])
time += run
remaining[name] -= run
while i < len(pending) and pending[i][1] <= time:
queue.append(pending[i][0]); i += 1
if remaining[name] > 0:
queue.append(name)
else:
finish[name] = time
return waits(jobs, finish)
jobs = [("A", 0, 8), ("B", 1, 4), ("C", 2, 2), ("D", 3, 6)]
for result in (fcfs(jobs), round_robin(jobs, 3)):
print(result, sum(result.values()) / len(result))
New arrivals are added to the queue before the job that has just used its slice, which is the rule used in worked example 9. Changing that order would change the results, so it is part of the design.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | fcfs on A, B, C, D | waits 0, 7, 10, 11; average 7.0 | Matches worked example 6 |
| 2 | round_robin with quantum 3 | waits 12, 10, 4, 9; average 8.75 | Matches worked example 9 |
| 3 | round_robin with quantum 8 | the same as FCFS, average 7.0 | A slice longer than every burst is FCFS |
| 4 | fcfs on P 0 5, Q 1 3, R 2 1 | waits 0, 4, 6; average 3.33 | Matches the check yourself |
| 5 | fcfs on X arriving at 5, burst 2 | wait 0 | The processor idles until X arrives |
| 6 | round_robin with quantum 4 | average 7.5 | A different slice gives a different average |
| 7 | round_robin with quantum 1 | every job finishes, waits all 0 or more | Very short slices still finish every job |
Evaluation
Every test agrees with the worked examples, and test 3 confirms a useful fact: round robin with a large enough slice behaves exactly like FCFS. Test 5 shows the program copes with an idle processor.
The simulation ignores the time taken to switch between jobs, which in a real system makes very small slices wasteful. An improvement would add a switching cost to every change of job, and show how the best slice size balances responsiveness against that overhead.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. List four jobs that an operating system carries out.
Worked solution to Q1
An operating system manages memory, schedules programs on the processor, handles interrupts and manages files. It also controls input and output devices, provides security and offers a user interface.
Q2. Explain the difference between paging and segmentation.
Worked solution to Q2
Paging divides memory and programs into fixed-size blocks, so any page fits any frame. Segmentation divides a program into logical parts of different sizes, such as code and data, each kept together in memory.
Q3. Describe the purpose of a device driver.
Worked solution to Q3
A device driver lets the operating system control a particular piece of hardware. It translates the operating system's general requests into the specific commands that device understands, so new hardware needs only a new driver.
Rung 2: Application
Q4. Pages are 2,048 bytes and page 1 is in frame 6. Translate the virtual address 3,000.
Worked solution to Q4
The page is 3000 DIV 2048 = 1, and the offset is 3000 MOD 2048 = 952. Frame 6 starts at 6 × 2,048 = 12,288, so the physical address is 12,288 + 952 = 13,240.
Q5. A program of 5,000 bytes uses 1,024-byte pages. How many pages does it need, and how many bytes are wasted?
Worked solution to Q5
Since 5,000 ÷ 1,024 is about 4.9, the program needs 5 pages, which hold 5,120 bytes. The last page wastes 5,120 − 5,000 = 120 bytes of internal fragmentation.
Q6. Use shortest job first for jobs P, Q and R, arriving at 0, 1 and 2 and needing 5, 3 and 1 units. Find the waiting times.
Worked solution to Q6
P runs first, 0 to 5, as the only job ready at time 0. At 5, R is shortest, so it runs 5 to 6, then Q runs 6 to 9. The waits are P 0, Q 5 and R 3, an average of 8 ÷ 3, about 2.67.
Q7. With 3 frames, count the FIFO page faults for the reference string 1, 2, 3, 1, 4, 2, 5, 1.
Worked solution to Q7
Pages 1, 2 and 3 fault and fill the frames, and 1 is then a hit. Next 4 replaces 1, the oldest, and 2 is a hit. Then 5 replaces 2 and 1 replaces 3. That is 6 faults in total.
Rung 3: Analysis
Q8. Count the LRU page faults for the reference string in Q7, and compare with FIFO.
Worked solution to Q8
Pages 1, 2 and 3 fault, and 1 is a hit. Then 4 replaces 2, the least recently used, and 2 faults, replacing 3. Next 5 replaces 1, and 1 replaces 4. That is 7 faults, one more than FIFO for this string.
Q9. Explain why shortest remaining time can make a long job wait a very long time.
Worked solution to Q9
Whenever a shorter job arrives, it takes over the processor. If short jobs keep arriving, the long job is pre-empted again and again and may wait indefinitely. This is called starvation.
Q10. A timer interrupt occurs every 5 ms and its routine takes 0.15 ms. What percentage of processor time does it use?
Worked solution to Q10
In each 5 ms period, the routine uses 0.15 ms of processor time. The fraction is 0.15 ÷ 5 = 0.03, which is 3% of the processor's time, leaving 97% for programs.
Q11. Explain why a computer with too little RAM can suffer disk thrashing.
Worked solution to Q11
With little RAM, pages must be moved to disk to make room, but they are soon needed again. The computer spends most of its time swapping pages between RAM and the slow disk, and very little doing useful work.
Rung 4: Stretch
Q12. Find the average waiting time for the four jobs of worked example 6 with round robin and a time slice of 4.
Worked solution to Q12
The order is A 0–4, B 4–8, C 8–10, D 10–14, A 14–18 and D 18–20. B finishes at 8 and C at 10, while A finishes at 18 and D at 20. The waits are A 10, B 3, C 6 and D 11, an average of 30 ÷ 4 = 7.5.
Q13. Show that FIFO with the reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 makes more faults with 4 frames than with 3.
Worked solution to Q13
With 3 frames, the pages 1, 2, 3, 4, 1, 2, 5, 3 and 4 all fault, while 1, 2 and 5 hit, giving 9 faults. With 4 frames, the first four fault, 1 and 2 hit, and then 5, 1, 2, 3, 4 and 5 all fault, giving 10. This is Belady's anomaly.
Q14. A charity's closed source suite costs £60 per computer per year. Find the cost for 35 computers over 4 years.
Worked solution to Q14
Each year costs 35 × £60 = £2,100, because every computer needs its own licence. Over 4 years the total is 4 × £2,100 = £8,400, compared with nothing in licence fees for an open source suite.
Exam practice
Exam technique and worked answer workshop
Scheduling questions are best answered with a Gantt chart. Draw a time line, mark each job's slices, then read off finish times and work out waits as finish minus arrival minus burst. Show the average with its working, because the method marks are worth as much as the answer.
For paging, write the DIV and MOD steps separately and say which frame the page is in before calculating the physical address. For page replacement, write the contents of the frames after every reference and mark each fault.
When comparing algorithms or types of operating system, link each to a situation. Round robin "is fair" earns little; "round robin gives every user a turn within one time slice, so an interactive system stays responsive" earns the mark.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
State four functions of an operating system.
Mark scheme for exam question 1
- B1 memory management
- B1 processor scheduling
- B1 handling interrupts
- B1 any one of: file management, managing peripherals with drivers, security, providing a user interface
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
Pages are 1,024 bytes. The page table maps pages 0, 1 and 2 to frames 5, 9 and 1. It maps page 3 to frame 6 and page 4 to frame 2.
(a) Translate the virtual address 5,000, showing the page and offset. [4]
(b) State what happens when the program uses virtual address 9,000. [1]
Mark scheme for exam question 2
- B1 page = 5000 DIV 1024 = 4
- B1 offset = 5000 MOD 1024 = 904
- M1 frame 2, so 2 × 1024 + 904
- A1 2,952
- B1 page 8 is not in the table, so a page fault occurs and the page is loaded from disk
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
Jobs A, B, C and D arrive at times 0, 1, 2 and 3, needing 8, 4, 2 and 6 units. They are scheduled first come, first served. Give each job's waiting time and the average waiting time.
Mark scheme for exam question 3
- B1 A waits 0
- B1 B waits 7
- B1 C waits 10
- B1 D waits 11
- B1 average 7
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
The same jobs are scheduled by round robin with a time slice of 3, new arrivals joining the queue before a job that has just used its slice.
(a) Give the order in which the slices run, with their times. [2]
(b) Calculate the average waiting time. [2]
(c) Give one advantage of round robin over first come, first served. [1]
Mark scheme for exam question 4
- B1 A 0–3, B 3–6, C 6–8, D 8–11
- B1 A 11–14, B 14–15, D 15–18, A 18–20
- M1 waits A 12, B 10, C 4, D 9
- A1 average 8.75
- B1 no job holds the processor for long, so the system stays responsive to every user
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A school is setting up a server that many students use at once for coursework and short quizzes. Discuss which scheduling algorithm the server's operating system should use.
Mark scheme for exam question 5
Level 3 (5–6 marks): a comparison of at least three algorithms, each linked to the server's mix of users and jobs, covering responsiveness, average waiting time and starvation. The answer reaches a justified recommendation. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct description of at least two algorithms with some link to the server. The comparison or the recommendation is limited.
Level 1 (1–2 marks): some relevant points, such as describing round robin, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- many users at once need a responsive system, so each needs a regular turn
- first come, first served lets one long job block every user behind it
- shortest job first and shortest remaining time give low average waits
- but they need job lengths in advance, and long jobs may starve
- round robin gives every user a turn within one time slice, so it stays responsive
- round robin's average waiting time can be higher
- the time slice must balance responsiveness against the cost of switching jobs
- a multilevel feedback queue keeps short quiz jobs fast while coursework runs later
- recommendation: round robin or a multilevel feedback queue
Annotated model answer: exam question 5
"Many students use the server at once, so it must respond to each of them quickly. First come, first served would let one long job, such as compiling a large project, block every student behind it, so it is unsuitable." (FCFS rejected, with a reason.)
"Shortest job first or shortest remaining time would give the lowest average waits, and quick quiz answers would be handled fast. But the server cannot know how long each job will take, and long coursework jobs could starve if short ones keep arriving." (SJF and SRT weighed.)
"Round robin gives every job a turn within one time slice, so every student sees a response. Its average wait can be higher, and the slice must be long enough that switching jobs does not waste too much time." (Round robin, with its trade-off.)
"A multilevel feedback queue combines the best of these: short quiz jobs stay at high priority and finish quickly, while long jobs move down and still get regular turns. That is the best choice for this server." (A justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It compares four algorithms against the server's needs and reaches a reasoned choice.
Exam question 6 (5 marks · Paper 01 · about 7 minutes)
A program uses pages in the order 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, with 3 frames, initially empty.
(a) Count the page faults with first in, first out. [2]
(b) Count the page faults with least recently used. [2]
(c) Explain why LRU usually performs better. [1]
Mark scheme for exam question 6
- M1 frames traced, removing the oldest page each time
- A1 10 faults
- M1 frames traced, removing the least recently used page each time
- A1 9 faults
- B1 recently used pages are likely to be used again soon, so LRU keeps them
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
Describe how an interrupt is handled by the processor and operating system.
Mark scheme for exam question 7
- B1 the processor checks for interrupts at the end of each fetch-decode-execute cycle
- B1 if the interrupt has a higher priority, the register contents, including the PC, are saved on the stack
- B1 the address of the interrupt service routine is loaded into the PC and the routine runs
- B1 the saved values are restored from the stack and the original program continues
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Jobs are stored in arrays arrival and burst, already sorted by arrival time, with n jobs. Write a function fcfsAverageWait(arrival, burst, n) that returns the average waiting time under first come, first served.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a time variable and a total wait, both starting at 0
- B1 a loop over all n jobs
- B1 the time moves on to the job's arrival if the processor is idle
- M1 each wait found as the start time minus the arrival, and added to the total
- A1 the time increased by the burst, and the total divided by n returned
Annotated model answer: exam question 8
function fcfsAverageWait(arrival, burst, n)
time = 0
total = 0
for i = 0 to n - 1
if time < arrival[i] then
time = arrival[i]
endif
total = total + (time - arrival[i])
time = time + burst[i]
next i
return total / n
endfunction
The header earns the first mark, and setting time and total to 0 the second. The loop over every job earns the third, and moving time forward when the processor is idle earns the fourth. Each job's wait, its start time minus its arrival, earns the method mark, and moving time on by the burst and returning the average earns the last.
Connections
Synoptic link
Interrupts and the stack come from Processor architecture and performance and Arrays, records, stacks and queues. The scheduler's ready queue is a queue, and multilevel feedback queues are priority queues. Paging uses DIV and MOD exactly as taught in Programming constructs.
Virtual memory depends on the storage devices in Types of processor, input, output and storage, and explains why adding RAM cures thrashing. The open and closed source debate returns in Legal, moral, ethical and cultural issues, alongside software licensing and copyright law.
Synoptic question 1. A computer's disk takes 10 ms to load a page, and RAM takes 100 ns. If 1 access in 100,000 is a page fault, find the average access time.
Answer to synoptic question 1
The average is 100 ns plus one hundred-thousandth of 10 ms. Since 10 ms is 10,000,000 ns, that extra part is 100 ns, so the average is 200 ns. Even very rare page faults double the average, which is why thrashing is so damaging.
Recap
Recap and next step
- The operating system manages memory, the processor, interrupts, files, devices and security, and gives each program a safe, separate share of the machine.
- Paging splits memory into equal frames: page = address DIV s, offset = address MOD s, and physical address = frame × s + offset. Segmentation uses logical parts of different sizes.
- A page fault loads a page from disk; FIFO removes the oldest page and LRU the least recently used, and too many faults cause thrashing.
- Waiting time = turnaround − burst; FCFS is simple, SJF and SRT lower the average, and round robin keeps every user responsive.
- Interrupts are checked after each cycle; registers are saved on the stack and an ISR runs. The BIOS boots the computer, drivers control devices, and virtual machines run whole systems in software.
- Applications do tasks for users and utilities maintain the computer; open source code is published under a licence, closed source code is kept private.
Next chapter: Translators and programming paradigms explains how compilers, interpreters and assemblers turn source code into programs the operating system can run.
For your exam board
OCR A Level Computer Science (H446): this chapter covers operating systems, memory management, paging, segmentation, virtual memory, interrupts, scheduling, types of operating system, the BIOS, device drivers and virtual machines in section 1.2.1, Systems software, and applications, utilities and open and closed source software in section 1.2.2, Applications generation, in Component 01.
AQA A Level Computer Science (7517): the role of the operating system, system software, utility programs, the handling of interrupts and the management of processors, memory and devices appear in the fundamentals of computer systems section, assessed on Paper 2.