Book 3 · Chapter 16
System Software
B3·16This 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.
For the whole chapter
- Topic pageSystem Software
B3·16·T - QuizSystem Software (A2)
B3·16·Q1 - LabReverse Polish & BNF (Compiler Lab)
B3·16·X1 - LabScheduling & paging simulator
B3·16·X2
§16.1 Purposes of an operating system · Memory management
Short code B3·16·1
- FlashcardsFlashcards §16.1: OS — processes, scheduling & interrupts
B3·16·F1 - FlashcardsFlashcards §16.1: OS — memory management
B3·16·F2 - Past-paper questionsPast-paper questions §16.1 (purposes-of-an-operating-system)
- Past-paper questionsPast-paper questions §16.1 (memory-management)
§16.2 Translation software
Short code B3·16·2
- FlashcardsFlashcards §16.2: Compilation stages, BNF & RPN
B3·16·F3 - Past-paper questionsPast-paper questions §16.2 (translation-software)
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)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
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)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
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)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
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')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
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))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
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: ", AnalysedOutput
7 4 1 -2 Statements analysed: 13
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)Output
Total | identifier 1 ← | assignment operator Total | identifier 1 + | arithmetic operator Price | identifier 2 * | arithmetic operator 2 | integer literal symbol table: ['Total', 'Price']
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 Total60 * 60 is worked out on every pass of the loop, although it never changes.Output
36000
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 TotalOutput
36000
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))Output
CD405 True DA00 True A7 False AB False AE12 False ab7 False
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 iOutput
(q + r) (p * (q + r)) (s - t) ((p * (q + r)) / (s - t))
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}))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
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 i8 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
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}))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
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.


