OS Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run and compare your output with the "Expected" lines. The Python exercises are small simulations of what the kernel does; the bash exercises run on a real Linux system. Try for a few minutes before opening a solution.
| # | Exercise | Topics |
|---|---|---|
| 1 | FCFS waiting times | CPU Scheduling |
| 2 | Address translation | Virtual Memory & Paging |
| 3 | FIFO vs LRU | Page Replacement |
| 4 | First-fit allocator | Memory Management |
| 5 | Deadlock detection | Synchronization & Deadlocks |
| 6 | Service start order | Windows Services, init & systemd |
| 7 | ACL evaluation | Windows Users, UAC & ACLs |
| 8 | Permission bits | Linux Users & Permissions |
| 9 | Memory report | /proc & /sys |
| 10 | Process states | Processes |
1. FCFS waiting times
Four jobs arrive as (name, arrival, burst). Simulate first-come, first-served scheduling: each job starts when the CPU is free and it has arrived. Print each job's start time, finish time and waiting time (start - arrival), then the average wait.
Expected:
A: start 0, finish 8, waited 0
B: start 8, finish 12, waited 7
C: start 12, finish 21, waited 10
D: start 21, finish 26, waited 18
average wait: 8.75jobs = [("A", 0, 8), ("B", 1, 4), ("C", 2, 9), ("D", 3, 5)]
t = 0
total = 0
for name, arrival, burst in jobs:
start = 0 # TODO: when does this job start?
wait = 0 # TODO
print(f"{name}: start {start:>2}, finish {t:>2}, waited {wait:>2}")
print(f"average wait: {total / len(jobs):.2f}")A: start 0, finish 0, waited 0
B: start 0, finish 0, waited 0
C: start 0, finish 0, waited 0
D: start 0, finish 0, waited 0
average wait: 0.00
Show solution
jobs = [("A", 0, 8), ("B", 1, 4), ("C", 2, 9), ("D", 3, 5)]
t = 0
total = 0
for name, arrival, burst in jobs:
start = max(t, arrival)
wait = start - arrival
t = start + burst
total += wait
print(f"{name}: start {start:>2}, finish {t:>2}, waited {wait:>2}")
print(f"average wait: {total / len(jobs):.2f}")The long job A at the front makes everyone wait: the convoy effect. Running the short jobs first (SJF) would lower the average.
2. Address translation
Pages are 4 KiB (4096 bytes). Split each virtual address into a page number and an offset, look the page up in the page table and build the physical address frame * 4096 + offset. Pages mapped to None (or missing) cause a page fault.
Expected:
0x00010 -> page 0 offset 0x010 -> 0x05010
0x01a2c -> page 1 offset 0xa2c -> 0x09a2c
0x02004 -> page 2: PAGE FAULT
0x03fff -> page 3 offset 0xfff -> 0x02fff
0x05000 -> page 5: PAGE FAULTPAGE = 4096
page_table = {0: 5, 1: 9, 2: None, 3: 2}
def translate(vaddr):
page, offset = 0, 0 # TODO: divmod
frame = 0 # TODO: look up; fault if None or missing
return f"0x{vaddr:05x} -> page {page} offset 0x{offset:03x} -> 0x{frame * PAGE + offset:05x}"
for v in [0x00010, 0x01a2c, 0x02004, 0x03fff, 0x05000]:
print(translate(v))0x00010 -> page 0 offset 0x000 -> 0x00000
0x01a2c -> page 0 offset 0x000 -> 0x00000
0x02004 -> page 0 offset 0x000 -> 0x00000
0x03fff -> page 0 offset 0x000 -> 0x00000
0x05000 -> page 0 offset 0x000 -> 0x00000
Show solution
PAGE = 4096
page_table = {0: 5, 1: 9, 2: None, 3: 2}
def translate(vaddr):
page, offset = divmod(vaddr, PAGE)
frame = page_table.get(page)
if frame is None:
return f"0x{vaddr:05x} -> page {page}: PAGE FAULT"
return f"0x{vaddr:05x} -> page {page} offset 0x{offset:03x} -> 0x{frame * PAGE + offset:05x}"
for v in [0x00010, 0x01a2c, 0x02004, 0x03fff, 0x05000]:
print(translate(v))With 4 KiB pages the offset is simply the last three hex digits, and the page number is everything in front of them. That's why page sizes are powers of two.
3. FIFO vs LRU
Count the page faults for the reference string with FIFO and LRU replacement, for 3 and 4 frames.
Expected:
3 frames: FIFO 10 faults, LRU 9 faults
4 frames: FIFO 7 faults, LRU 6 faultsrefs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
def fifo(refs, frames):
return 0 # TODO: evict the page that was loaded first
def lru(refs, frames):
return 0 # TODO: evict the page that was used least recently
for f in (3, 4):
print(f"{f} frames: FIFO {fifo(refs, f)} faults, LRU {lru(refs, f)} faults")3 frames: FIFO 0 faults, LRU 0 faults
4 frames: FIFO 0 faults, LRU 0 faults
Show solution
from collections import OrderedDict
refs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
def fifo(refs, frames):
mem, faults = [], 0
for p in refs:
if p not in mem:
faults += 1
if len(mem) == frames:
mem.pop(0) # oldest loaded page
mem.append(p)
return faults
def lru(refs, frames):
mem, faults = OrderedDict(), 0
for p in refs:
if p in mem:
mem.move_to_end(p) # a hit makes the page "recent"
else:
faults += 1
if len(mem) == frames:
mem.popitem(last=False) # least recently used
mem[p] = True
return faults
for f in (3, 4):
print(f"{f} frames: FIFO {fifo(refs, f)} faults, LRU {lru(refs, f)} faults")The only difference is what a hit does: FIFO ignores it, LRU moves the page to the "recent" end.
4. First-fit allocator
Free memory consists of holes (start, length). For each request, use the first hole that is large enough, carve the request from its start and shrink the hole. Print where each request went and the remaining holes.
Expected:
A (120) -> address 300
B (40) -> address 0
C (260) -> no hole big enough
D (90) -> address 420
E (200) -> no hole big enough
free holes: [(40, 60), (200, 50), (510, 90), (700, 120)]holes = [(0, 100), (200, 50), (300, 300), (700, 120)]
requests = [("A", 120), ("B", 40), ("C", 260), ("D", 90), ("E", 200)]
for name, size in requests:
# TODO: find the first hole with length >= size, update it
print(f"{name} ({size}) -> no hole big enough")
print("free holes:", holes)A (120) -> no hole big enough
B (40) -> no hole big enough
C (260) -> no hole big enough
D (90) -> no hole big enough
E (200) -> no hole big enough
free holes: [(0, 100), (200, 50), (300, 300), (700, 120)]
Show solution
holes = [(0, 100), (200, 50), (300, 300), (700, 120)]
requests = [("A", 120), ("B", 40), ("C", 260), ("D", 90), ("E", 200)]
for name, size in requests:
for i, (start, length) in enumerate(holes):
if length >= size:
print(f"{name} ({size}) -> address {start}")
holes[i] = (start + size, length - size)
break
else:
print(f"{name} ({size}) -> no hole big enough")
print("free holes:", [h for h in holes if h[1] > 0])At the end 320 bytes are free in total, yet a 200-byte request fails: that's external fragmentation. Paging avoids it for user memory by using fixed-size frames.
5. Deadlock detection
A wait-for graph maps each blocked thread to the thread holding the lock it wants. A cycle means deadlock. Write find_cycle that returns the cycle as a list (starting from the alphabetically first thread that is on it), or None.
Expected:
no deadlock
deadlock: T1 -> T2 -> T4 -> T3 -> T1def find_cycle(waits_for):
return None # TODO: follow the edges from each start node
ok = {"T1": "T2", "T2": "T3"}
bad = {"T1": "T2", "T2": "T4", "T3": "T1", "T4": "T3"}
for g in (ok, bad):
c = find_cycle(g)
print("deadlock: " + " -> ".join(c) if c else "no deadlock")no deadlock
no deadlock
Show solution
def find_cycle(waits_for):
for start in sorted(waits_for):
path, node = [start], waits_for.get(start)
while node is not None and node not in path:
path.append(node)
node = waits_for.get(node)
if node == start:
return path + [start]
return NoneEach thread waits for at most one other here, so following the single outgoing edge is enough. With several locks per thread you'd need a full depth-first search.
6. Service start order
Each service lists the services it depends on. Print an order in which they can all be started (dependencies first, visiting names alphabetically), and the stop order.
Expected:
start: disk db net backup cache web
stop: web cache backup net db diskdeps = {"web": ["db", "cache"], "db": ["disk"], "cache": ["net"],
"net": [], "disk": [], "backup": ["db", "net"]}
def start_order(deps):
return sorted(deps) # TODO: depth-first, dependencies before the service
order = start_order(deps)
print("start:", " ".join(order))
print("stop: ", " ".join(reversed(order)))start: backup cache db disk net web
stop: web net disk db cache backup
Show solution
def start_order(deps):
order, done = [], set()
def visit(name):
if name in done:
return
for d in sorted(deps[name]):
visit(d)
done.add(name)
order.append(name)
for name in sorted(deps):
visit(name)
return orderThis is a topological sort, the same thing the Windows SCM and systemd do with service dependencies.
7. ACL evaluation
check walks an ACL in order: a matching deny ACE that covers a wanted right denies, matching allow ACEs add rights, and access is allowed once all wanted rights are granted. Lee is in staff, contractors and everyone. Implement check and canonical (deny ACEs before allow ACEs) and show how the order changes the result.
Expected:
as given lee read: ALLOW, lee write: ALLOW
canonical lee read: ALLOW, lee write: DENYREAD, WRITE = 1, 2
acl = [("allow", "staff", READ | WRITE), ("deny", "contractors", WRITE), ("allow", "everyone", READ)]
def check(groups, wanted, acl):
return "DENY" # TODO
def canonical(acl):
return acl # TODO: deny entries first
lee = {"lee", "staff", "contractors", "everyone"}
for label, rules in [("as given", acl), ("canonical", canonical(acl))]:
print(f"{label:<10} lee read: {check(lee, READ, rules)}, lee write: {check(lee, WRITE, rules)}")as given lee read: DENY, lee write: DENY
canonical lee read: DENY, lee write: DENY
Show solution
def check(groups, wanted, acl):
granted = 0
for kind, sid, mask in acl:
if sid not in groups:
continue
if kind == "deny" and mask & wanted & ~granted:
return "DENY"
if kind == "allow":
granted |= mask
if granted & wanted == wanted:
return "ALLOW"
return "DENY"
def canonical(acl):
return [a for a in acl if a[0] == "deny"] + [a for a in acl if a[0] == "allow"]In the original order the staff allow grants write before the deny is ever reached. Windows editors always save ACLs in canonical order so that deny entries win.
8. Permission bits
Write a bash function to_octal that turns a symbolic permission string such as rwxr-x--- into its octal form (750). Then use it with chmod on a new file and check the result with stat.
Expected:
rwxr-x--- = 750 -> -rwxr-x---
rw-r--r-- = 644 -> -rw-r--r--
rwx------ = 700 -> -rwx------
r--r----- = 440 -> -r--r-----to_octal() {
echo "000" # TODO: r = 4, w = 2, x = 1 for each group of three
}
for p in rwxr-x--- rw-r--r-- rwx------ r--r-----; do
touch "f-$p"
chmod "$(to_octal "$p")" "f-$p"
echo "$p = $(to_octal "$p") -> $(stat -c '%A' "f-$p")"
donerwxr-x--- = 000 -> ----------
rw-r--r-- = 000 -> ----------
rwx------ = 000 -> ----------
r--r----- = 000 -> ----------
Show solution
to_octal() {
local s=$1 out="" i d
for i in 0 3 6; do
d=0
[[ ${s:i:1} == r ]] && ((d += 4))
[[ ${s:i+1:1} == w ]] && ((d += 2))
[[ ${s:i+2:1} == x ]] && ((d += 1))
out+=$d
done
echo "$out"
}${s:i:1} is bash's substring expansion: one character at position i. The three digits are user, group and others.
9. Memory report
meminfo.txt is a saved copy of a machine's /proc/meminfo (values in kB). Print used RAM (MemTotal - MemAvailable) in GiB with the percentage, the page cache (Cached + Buffers) and the used swap in MiB.
Expected:
RAM: 6.1 GiB of 15.5 GiB used (39%)
cache: 7.7 GiB
swap: 1024 MiB usedcat > meminfo.txt <<'EOF'
MemTotal: 16303428 kB
MemFree: 1203320 kB
MemAvailable: 9876544 kB
Buffers: 412300 kB
Cached: 7655040 kB
SwapTotal: 4194300 kB
SwapFree: 3145724 kB
EOF
awk '{ v[$1] = $2 }
END {
# TODO: compute the three lines from v["MemTotal:"], v["MemAvailable:"], ...
printf "RAM: %.1f GiB of %.1f GiB used (%d%%)\n", 0, 0, 0
}' meminfo.txtRAM: 0.0 GiB of 0.0 GiB used (0%)
Show solution
awk '{ v[$1] = $2 }
END {
used = v["MemTotal:"] - v["MemAvailable:"]
printf "RAM: %.1f GiB of %.1f GiB used (%d%%)\n", used/1048576, v["MemTotal:"]/1048576, used*100/v["MemTotal:"]
printf "cache: %.1f GiB\n", (v["Cached:"] + v["Buffers:"])/1048576
swap = v["SwapTotal:"] - v["SwapFree:"]
printf "swap: %d MiB used\n", swap/1024
}' meminfo.txtUse MemAvailable, not MemFree: Linux fills free RAM with page cache, which it can drop at any moment, so "free" memory is almost always low on a healthy system.
10. Process states
ps.txt is a saved ps -eo pid,ppid,stat,comm listing. Count the processes per state (the first letter of STAT: R running, S sleeping, D uninterruptible I/O wait, Z zombie, I idle kernel thread), sorted by letter, and print each zombie with its parent.
Expected:
D 1
I 1
R 1
S 5
Z 1
zombie: 1202 parent 1200cat > ps.txt <<'EOF'
PID PPID STAT COMMAND
1 0 Ss systemd
412 1 Ss sshd
901 412 Ss bash
955 901 R+ ps
1200 1 Sl nginx
1201 1200 S nginx
1202 1200 Z nginx
1300 1 D jbd2
1301 1 I< kworker
EOF
# TODO: skip the header, count substr($3, 1, 1), then find the zombies
tail -n +2 ps.txt | wc -l9
Show solution
tail -n +2 ps.txt | awk '{ n[substr($3, 1, 1)]++ } END { for (k in n) print k, n[k] }' | sort
tail -n +2 ps.txt | awk 'substr($3, 1, 1) == "Z" { print "zombie:", $1, "parent", $2 }'A zombie has already exited; it stays in the table until its parent (here nginx 1200) calls wait(). Killing the zombie does nothing; fixing or restarting the parent does.
Learn more: Mini Project: Scheduler & Memory Simulator · CPU Scheduling · Page Replacement
Test yourself
In exercise 4, 320 bytes are free but a 200-byte request fails. What is this called?
- Internal fragmentation
- External fragmentation
- Thrashing
- A page fault
Which field of /proc/meminfo best answers "how much memory can new programs still get?"
- MemFree
- MemAvailable
- Cached
- SwapFree
How do you get rid of a zombie process?
- kill -9 the zombie
- Make its parent call wait() (or end the parent so init adopts and reaps it)
- Reboot only
- Delete it from /proc