Skip to content
Book 3: Advanced Theory

Book 3 · Chapter 16

System Software

§16.1§16.2Core · ≈ 13 m · ↘B3·16

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

For the whole chapter

§16.1 Purposes of an operating system · Memory management

Short code B3·16·1

§16.2 Translation software

Short code B3·16·2

Part A: Making the most of the computer's resources

Short code B3·16·10

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

How the user interface hides the hardware

Short code B3·16·11

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Processes and their three states

Short code B3·16·12

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Why processes need scheduling

Short code B3·16·13

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

First come first served and shortest job first

Short code B3·16·14

def run(procs, algo, q=2):
    rem = {n: b for n, a, b in procs}; arr = {n: a for n, a, b in procs}
    t, ready, done, gantt, seen, cur = 0, [], {}, [], set(), None
    def admit(now):
        for n, a, b in procs:
            if a <= now and n not in seen:
                seen.add(n); ready.append(n)
    def bar(n, s, e):
        if gantt and gantt[-1][0] == n and gantt[-1][2] == s: gantt[-1] = (n, gantt[-1][1], e)
        else: gantt.append((n, s, e))
    while len(done) < len(procs):
        admit(t)
        if not ready: t += 1; continue
        if algo == 'SRT':
            n = min(ready, key=lambda x: (rem[x], x != cur, arr[x])); cur = n
            bar(n, t, t + 1); t += 1; rem[n] -= 1
            if rem[n] == 0: ready.remove(n); done[n] = t; cur = None
            continue
        if algo == 'SJF': ready.sort(key=lambda x: (rem[x], arr[x]))
        n = ready.pop(0)
        s = min(q, rem[n]) if algo == 'RR' else rem[n]
        bar(n, t, t + s); t += s; rem[n] -= s
        admit(t)
        if rem[n]: ready.append(n)
        else: done[n] = t
    rows = [(n, done[n] - a, done[n] - a - b) for n, a, b in procs]
    return gantt, rows
P = [('A', 0, 6), ('B', 1, 3), ('C', 3, 4), ('D', 5, 2)]
for algo in ('FCFS', 'SJF', 'RR', 'SRT'):
    g, rows = run(P, algo, 2)
    print(algo, ' '.join(f'{n}{s}-{e}' for n, s, e in g))
    print('  turnaround', [t for n, t, w in rows], 'waiting', [w for n, t, w in rows], 'average', sum(w for n, t, w in rows) / 4)
Notes check: processes A–D (arrivals 0, 1, 3, 5; bursts 6, 3, 4, 2) under all four routines (RR slice 2 ms). It prints each Gantt chart, then each process's waiting time and the average.

Output

FCFS A0-6 B6-9 C9-13 D13-15
  turnaround [6, 8, 10, 10] waiting [0, 5, 6, 8] average 4.75
SJF A0-6 D6-8 B8-11 C11-15
  turnaround [6, 10, 12, 3] waiting [0, 7, 8, 1] average 4.0
RR A0-2 B2-4 A4-6 C6-8 B8-9 D9-11 A11-13 C13-15
  turnaround [13, 8, 12, 6] waiting [7, 5, 8, 4] average 6.0
SRT A0-1 B1-4 C4-5 D5-7 C7-10 A10-15
  turnaround [15, 3, 7, 2] waiting [9, 0, 3, 0] average 3.0
Run and checked before printing
def run(procs, algo, q=2):
    rem = {n: b for n, a, b in procs}; arr = {n: a for n, a, b in procs}
    t, ready, done, gantt, seen, cur = 0, [], {}, [], set(), None
    def admit(now):
        for n, a, b in procs:
            if a <= now and n not in seen:
                seen.add(n); ready.append(n)
    def bar(n, s, e):
        if gantt and gantt[-1][0] == n and gantt[-1][2] == s: gantt[-1] = (n, gantt[-1][1], e)
        else: gantt.append((n, s, e))
    while len(done) < len(procs):
        admit(t)
        if not ready: t += 1; continue
        if algo == 'SRT':
            n = min(ready, key=lambda x: (rem[x], x != cur, arr[x])); cur = n
            bar(n, t, t + 1); t += 1; rem[n] -= 1
            if rem[n] == 0: ready.remove(n); done[n] = t; cur = None
            continue
        if algo == 'SJF': ready.sort(key=lambda x: (rem[x], arr[x]))
        n = ready.pop(0)
        s = min(q, rem[n]) if algo == 'RR' else rem[n]
        bar(n, t, t + s); t += s; rem[n] -= s
        admit(t)
        if rem[n]: ready.append(n)
        else: done[n] = t
    rows = [(n, done[n] - a, done[n] - a - b) for n, a, b in procs]
    return gantt, rows
P = [('P', 0, 4), ('Q', 1, 7), ('R', 2, 1)]
for algo in ('SJF', 'FCFS'):
    g, rows = run(P, algo)
    print(algo, ' '.join(f'{n}{s}-{e}' for n, s, e in g), [w for n, t, w in rows], sum(w for n, t, w in rows) / 3)
print(15 - 4, 15 - 4 - 3)
Notes check: the Mark Ladder (SJF) and its faded twin (FCFS) for P, Q, R; and the check question (arrives 4, needs 3, finishes 15).

Output

SJF P0-4 R4-5 Q5-12 [0, 4, 2] 2.0
FCFS P0-4 Q4-11 R11-12 [0, 3, 9] 4.0
11 8
Run and checked before printing

Round robin and shortest remaining time

Short code B3·16·15

def run(procs, algo, q=2):
    rem = {n: b for n, a, b in procs}; arr = {n: a for n, a, b in procs}
    t, ready, done, gantt, seen, cur = 0, [], {}, [], set(), None
    def admit(now):
        for n, a, b in procs:
            if a <= now and n not in seen:
                seen.add(n); ready.append(n)
    def bar(n, s, e):
        if gantt and gantt[-1][0] == n and gantt[-1][2] == s: gantt[-1] = (n, gantt[-1][1], e)
        else: gantt.append((n, s, e))
    while len(done) < len(procs):
        admit(t)
        if not ready: t += 1; continue
        if algo == 'SRT':
            n = min(ready, key=lambda x: (rem[x], x != cur, arr[x])); cur = n
            bar(n, t, t + 1); t += 1; rem[n] -= 1
            if rem[n] == 0: ready.remove(n); done[n] = t; cur = None
            continue
        if algo == 'SJF': ready.sort(key=lambda x: (rem[x], arr[x]))
        n = ready.pop(0)
        s = min(q, rem[n]) if algo == 'RR' else rem[n]
        bar(n, t, t + s); t += s; rem[n] -= s
        admit(t)
        if rem[n]: ready.append(n)
        else: done[n] = t
    rows = [(n, done[n] - a, done[n] - a - b) for n, a, b in procs]
    return gantt, rows
P = [('A', 0, 6), ('B', 1, 3), ('C', 3, 4), ('D', 5, 2)]
for algo in ('FCFS', 'SJF', 'RR', 'SRT'):
    g, rows = run(P, algo, 2)
    print(algo, ' '.join(f'{n}{s}-{e}' for n, s, e in g))
    print('  turnaround', [t for n, t, w in rows], 'waiting', [w for n, t, w in rows], 'average', sum(w for n, t, w in rows) / 4)
Notes check: processes A–D (arrivals 0, 1, 3, 5; bursts 6, 3, 4, 2) under all four routines (RR slice 2 ms). It prints each Gantt chart, then each process's waiting time and the average.

Output

FCFS A0-6 B6-9 C9-13 D13-15
  turnaround [6, 8, 10, 10] waiting [0, 5, 6, 8] average 4.75
SJF A0-6 D6-8 B8-11 C11-15
  turnaround [6, 10, 12, 3] waiting [0, 7, 8, 1] average 4.0
RR A0-2 B2-4 A4-6 C6-8 B8-9 D9-11 A11-13 C13-15
  turnaround [13, 8, 12, 6] waiting [7, 5, 8, 4] average 6.0
SRT A0-1 B1-4 C4-5 D5-7 C7-10 A10-15
  turnaround [15, 3, 7, 2] waiting [9, 0, 3, 0] average 3.0
Run and checked before printing

Choosing a scheduling routine

Short code B3·16·16

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Interrupts: the kernel in charge

Short code B3·16·17

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Paging and segmentation

Short code B3·16·18

size = 256
pages = {0: 5, 1: 2, 2: 6, 3: 7}
for a in (830, 300):
    p, off = divmod(a, size)
    print(a, 'page', p, 'offset', off, 'physical', pages[p] * size + off)
segs = {0: (4000, 1200), 1: (1500, 600), 2: (7000, 300)}
for s, off in ((1, 250), (2, 340)):
    base, length = segs[s]
    print((s, off), base + off if off < length else 'error: offset not less than length')
Notes check, address translation: paging (256-byte pages, page table 0→5, 1→2, 2→6, 3→7) for logical addresses 830 and 300, and the segment table for (1, 250) and (2, 340).

Output

830 page 3 offset 62 physical 1854
300 page 1 offset 44 physical 556
(1, 250) 1750
(2, 340) error: offset not less than length
Run and checked before printing

Virtual memory

Short code B3·16·19

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Page replacement and disk thrashing

Short code B3·16·20

def sim(refs, n, pol):
    frames, order, marks = [], [], []
    for p in refs:
        if p in frames:
            if pol == 'LRU':
                order.remove(p); order.append(p)
            marks.append('-')
            continue
        if len(frames) < n:
            frames.append(p); marks.append('F')
        else:
            v = order.pop(0); frames[frames.index(v)] = p; marks.append(f'F({v})')
        order.append(p)
    return marks
refs = [1, 2, 3, 1, 4, 1, 2, 5, 1, 2]
for pol in ('FIFO', 'LRU'):
    m = sim(refs, 3, pol)
    print(pol, ' '.join(m), sum(x.startswith('F') for x in m))
Notes check: page replacement with 3 frames for the reference string 1 2 3 1 4 1 2 5 1 2. It prints each page, then F (fault) and the page replaced, under FIFO and LRU.

Output

FIFO F F F - F(1) F(2) F(3) F(4) - - 7
LRU F F F - F(2) - F(3) F(4) - - 6
Run and checked before printing

Part B: How an interpreter runs a program

Short code B3·16·21

DECLARE Op : ARRAY[1:4] OF STRING
DECLARE Arg : ARRAY[1:4] OF INTEGER
DECLARE Line : INTEGER
DECLARE Acc : INTEGER
DECLARE Analysed : INTEGER
// the program to be interpreted: SET 10, SUB 3, OUT, JPOS 2
Op[1] ← "SET"
Arg[1] ← 10
Op[2] ← "SUB"
Arg[2] ← 3
Op[3] ← "OUT"
Arg[3] ← 0
Op[4] ← "JPOS"
Arg[4] ← 2
Acc ← 0
Analysed ← 0
Line ← 1
WHILE Line <= 4
   Analysed ← Analysed + 1
   CASE OF Op[Line]
      "SET"  : Acc ← Arg[Line]
      "SUB"  : Acc ← Acc - Arg[Line]
      "OUT"  : OUTPUT Acc
      "JPOS" : IF Acc > 0
                  THEN
                     Line ← Arg[Line] - 1
               ENDIF
   ENDCASE
   Line ← Line + 1
ENDWHILE
OUTPUT "Statements analysed: ", Analysed
The toy interpreter, in full. The four-line program is held as an operation and a value per line; the CASE statement is the interpreter's set of routines. Notice it analyses 13 statements to run a 4-line program.

Output

7
4
1
-2
Statements analysed: 13
Run and checked before printing

The stages of compilation

Short code B3·16·22

import re
src = 'Total ← Total + Price * 2  // add delivery'
code = src.split('//')[0]
symbols = []
for lex in re.findall(r'[A-Za-z]\w*|\d+|←|[-+*/]', code):
    if lex[0].isalpha():
        if lex not in symbols:
            symbols.append(lex)
        kind = 'identifier ' + str(symbols.index(lex) + 1)
    elif lex.isdigit():
        kind = 'integer literal'
    elif lex == '←':
        kind = 'assignment operator'
    else:
        kind = 'arithmetic operator'
    print(lex, '|', kind)
print('symbol table:', symbols)
Notes check: a minimal lexical analyser for the statement in the figure. Comment and spaces are removed, each lexeme is given a token and identifiers are entered once in the symbol table.

Output

Total | identifier 1
← | assignment operator
Total | identifier 1
+ | arithmetic operator
Price | identifier 2
* | arithmetic operator
2 | integer literal
symbol table: ['Total', 'Price']
Run and checked before printing

Syntax analysis, code generation and optimisation

Short code B3·16·23

DECLARE i : INTEGER
DECLARE Total : INTEGER
DECLARE Rate : INTEGER
Total ← 0
FOR i ← 1 TO 4
   Rate ← 60 * 60
   Total ← Total + i * Rate
NEXT i
OUTPUT Total
Before optimisation: 60 * 60 is worked out on every pass of the loop, although it never changes.

Output

36000
Run and checked before printing
DECLARE i : INTEGER
DECLARE Total : INTEGER
DECLARE Rate : INTEGER
Total ← 0
Rate ← 3600
FOR i ← 1 TO 4
   Total ← Total + i * Rate
NEXT i
OUTPUT Total
After optimisation: the constant is calculated once (by the compiler, as 3600) and moved out of the loop. Same output, four fewer multiplications at run time.

Output

36000
Run and checked before printing

Backus-Naur Form

Short code B3·16·24

import re
def grammar(text):
    g = {}
    for line in text.strip().splitlines():
        name, rhs = line.split('::=')
        g[name.strip()] = [re.findall(r'<[^>]+>|[^<>\s|]', alt) for alt in rhs.split('|')]
    return g
def ends(g, sym, s, i):
    if not sym.startswith('<'):
        return {i + 1} if s[i:i + 1] == sym else set()
    out = set()
    for alt in g[sym]:
        pos = {i}
        for item in alt:
            pos = {e for p in pos for e in ends(g, item, s, p)}
        out |= pos
    return out
def valid(text, start, s):
    return len(s) in ends(grammar(text), start, s, 0)
G = '''<code> ::= <letter><letter><number>
<number> ::= <digit> | <digit><number>
<letter> ::= A | B | C | D
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9'''
for s in ('CD405', 'DA00', 'A7', 'AB', 'AE12', 'ab7'):
    print(s, valid(G, '<code>', s))
Notes check, the product-code grammar, parsed: every string in the table, tested against exactly the four BNF rules.

Output

CD405 True
DA00 True
A7 False
AB False
AE12 False
ab7 False
Run and checked before printing

Syntax diagrams

Short code B3·16·25

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Reverse Polish Notation

Short code B3·16·26

DECLARE Item : ARRAY[1:9] OF STRING
DECLARE Stack : ARRAY[1:9] OF STRING
DECLARE Top : INTEGER
DECLARE i : INTEGER
DECLARE Left : STRING
DECLARE Right : STRING
// the RPN expression p q r + * s t - /, one item per element
Item[1] ← "p"
Item[2] ← "q"
Item[3] ← "r"
Item[4] ← "+"
Item[5] ← "*"
Item[6] ← "s"
Item[7] ← "t"
Item[8] ← "-"
Item[9] ← "/"
Top ← 0
FOR i ← 1 TO 9
   IF Item[i] = "+" OR Item[i] = "-" OR Item[i] = "*" OR Item[i] = "/"
      THEN
         Right ← Stack[Top]
         Left ← Stack[Top - 1]
         Top ← Top - 1
         Stack[Top] ← "(" & Left & " " & Item[i] & " " & Right & ")"
         OUTPUT Stack[Top]
      ELSE
         Top ← Top + 1
         Stack[Top] ← Item[i]
   ENDIF
NEXT i
RPN to infix with a stack of strings: each operator pops two sub-expressions and pushes them back joined, in brackets. The first popped is the right-hand one. Notice the last line is the whole expression.

Output

(q + r)
(p * (q + r))
(s - t)
((p * (q + r)) / (s - t))
Run and checked before printing
PREC = {'+': 1, '-': 1, '*': 2, '/': 2}
def rpn(expr):
    out, st = [], []
    for t in expr.split():
        if t in PREC:
            while st and st[-1] in PREC and PREC[st[-1]] >= PREC[t]:
                out.append(st.pop())
            st.append(t)
        elif t == '(':
            st.append(t)
        elif t == ')':
            while st[-1] != '(':
                out.append(st.pop())
            st.pop()
        else:
            out.append(t)
    return ' '.join(out + st[::-1])
for e in ('( A + B ) * C - D / E', '4 * ( 6 - 2 ) + 9 / 3', '( A - B ) * C'):
    print(rpn(e))
def infix(r):
    st = []
    for t in r.split():
        if t in PREC:
            b, a = st.pop(), st.pop(); st.append('(' + a + ' ' + t + ' ' + b + ')')
        else:
            st.append(t)
    return st[0]
print(infix('p q r + * s t - /'))
def ev(r, v):
    st, rows = [], []
    for t in r.split():
        if t in PREC:
            b, a = st.pop(), st.pop(); st.append({'+': a + b, '-': a - b, '*': a * b, '/': a // b}[t])
        else:
            st.append(v[t] if t in v else int(t))
        rows.append(' '.join(map(str, st)))
    return ' | '.join(rows)
print(ev('8 2 - 3 4 + * 6 /', {}))
print(ev('4 6 2 - * 9 3 / +', {}))
print(ev('a b + c *', {'a': 3, 'b': 5, 'c': 2}))
Notes check, every RPN in the chapter's notes: infix to RPN (the worked example, the check question, the Mark Ladder's twin), RPN back to infix, and the stack after each item for 8 2 - 3 4 + * 6 / and the faded twin a b + c * (a = 3, b = 5, c = 2).

Output

A B + C * D E / -
4 6 2 - * 9 3 / +
A B - C *
((p * (q + r)) / (s - t))
8 | 8 2 | 6 | 6 3 | 6 3 4 | 6 7 | 42 | 42 6 | 7
4 | 4 6 | 4 6 2 | 4 4 | 16 | 16 9 | 16 9 3 | 16 3 | 19
3 | 3 5 | 8 | 8 2 | 16
Run and checked before printing

Evaluating RPN with a stack

Short code B3·16·27

DECLARE IsOp : ARRAY[1:9] OF BOOLEAN
DECLARE Sym : ARRAY[1:9] OF CHAR
DECLARE Val : ARRAY[1:9] OF REAL
DECLARE Stack : ARRAY[1:9] OF REAL
DECLARE Top : INTEGER
DECLARE i : INTEGER
DECLARE Left : REAL
DECLARE Right : REAL
// 8 2 - 3 4 + * 6 /
FOR i ← 1 TO 9
   IsOp[i] ← FALSE
   Sym[i] ← ' '
   Val[i] ← 0
NEXT i
Val[1] ← 8
Val[2] ← 2
IsOp[3] ← TRUE
Sym[3] ← '-'
Val[4] ← 3
Val[5] ← 4
IsOp[6] ← TRUE
Sym[6] ← '+'
IsOp[7] ← TRUE
Sym[7] ← '*'
Val[8] ← 6
IsOp[9] ← TRUE
Sym[9] ← '/'
Top ← 0
FOR i ← 1 TO 9
   IF IsOp[i] = FALSE
      THEN
         Top ← Top + 1
         Stack[Top] ← Val[i]
      ELSE
         Right ← Stack[Top]
         Left ← Stack[Top - 1]
         Top ← Top - 1
         CASE OF Sym[i]
            '+' : Stack[Top] ← Left + Right
            '-' : Stack[Top] ← Left - Right
            '*' : Stack[Top] ← Left * Right
            '/' : Stack[Top] ← Left / Right
         ENDCASE
   ENDIF
   OUTPUT Stack[Top]
NEXT i
The RPN evaluator in full, with 8 2 - 3 4 + * 6 / loaded into the arrays. It outputs the top of the stack after each item.

Output

8
2
6
3
4
7
42
6
7
Run and checked before printing
PREC = {'+': 1, '-': 1, '*': 2, '/': 2}
def rpn(expr):
    out, st = [], []
    for t in expr.split():
        if t in PREC:
            while st and st[-1] in PREC and PREC[st[-1]] >= PREC[t]:
                out.append(st.pop())
            st.append(t)
        elif t == '(':
            st.append(t)
        elif t == ')':
            while st[-1] != '(':
                out.append(st.pop())
            st.pop()
        else:
            out.append(t)
    return ' '.join(out + st[::-1])
for e in ('( A + B ) * C - D / E', '4 * ( 6 - 2 ) + 9 / 3', '( A - B ) * C'):
    print(rpn(e))
def infix(r):
    st = []
    for t in r.split():
        if t in PREC:
            b, a = st.pop(), st.pop(); st.append('(' + a + ' ' + t + ' ' + b + ')')
        else:
            st.append(t)
    return st[0]
print(infix('p q r + * s t - /'))
def ev(r, v):
    st, rows = [], []
    for t in r.split():
        if t in PREC:
            b, a = st.pop(), st.pop(); st.append({'+': a + b, '-': a - b, '*': a * b, '/': a // b}[t])
        else:
            st.append(v[t] if t in v else int(t))
        rows.append(' '.join(map(str, st)))
    return ' | '.join(rows)
print(ev('8 2 - 3 4 + * 6 /', {}))
print(ev('4 6 2 - * 9 3 / +', {}))
print(ev('a b + c *', {'a': 3, 'b': 5, 'c': 2}))
Notes check, every RPN in the chapter's notes: infix to RPN (the worked example, the check question, the Mark Ladder's twin), RPN back to infix, and the stack after each item for 8 2 - 3 4 + * 6 / and the faded twin a b + c * (a = 3, b = 5, c = 2).

Output

A B + C * D E / -
4 6 2 - * 9 3 / +
A B - C *
((p * (q + r)) / (s - t))
8 | 8 2 | 6 | 6 3 | 6 3 4 | 6 7 | 42 | 42 6 | 7
4 | 4 6 | 4 6 2 | 4 4 | 16 | 16 9 | 16 9 3 | 16 3 | 19
3 | 3 5 | 8 | 8 2 | 16
Run and checked before printing

Past-paper practice

Short code B3·16·90

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Workbook 3: System Software

Short code W3·16 · Advanced Theory Workbook

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Ask Z about System Software
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook