Lesson 9 · Files, storage, I/O, and protection

Spooling and Buffering

Devices are slow and processes are fast. Buffering smooths one transfer through memory; spooling queues whole jobs on disk so one device can serve many processes.

Spooling and Buffering concept diagramLeft panel, buffering: a process and a device exchange data through two buffers in main memory. Right panel, spooling: three processes write whole print jobs to a queue on disk, and a printer takes them one at a time.buffering: RAM between device and processdiskmain memorybuffer 1buffer 2processdevice fills one buffer whilethe process empties the otherspooling: whole jobs queued on diskP1P2P3spool (disk)job Ajob Bjob Cprinterprocesses continue at once;the printer takes one job at a timebuffer: a few blocks in RAM for one transfer · spool: whole jobs on disk for a shared device
1

Why Operating Systems Need Buffering and Spooling

  1. Speed mismatch – producer and consumer run at different rates.
  2. Size mismatch – a device transfers in blocks, a program asks for bytes, or a network sends packets of a different size.
  3. Copy semantics – data handed to write() must not change if the program reuses its array straight away.
  4. Shared device – a printer cannot interleave two jobs, but many processes want it.

A CPU executes billions of instructions a second; a disk completes perhaps a hundred random reads; a printer produces a page every few seconds. If a process had to wait in lock-step for each device, it would spend almost all its time idle, and so would the device while the process computed.

Buffering and spooling both decouple the two sides by putting storage between them, so each can run at its own speed. They differ in scale: buffering holds a few blocks of one transfer in memory; spooling holds entire jobs from many processes on disk.

  • The first three are solved by buffering
  • The fourth is solved by spooling
  • Both trade memory or disk space for overlap and throughput
2

What Is Buffering?

A buffer is an area of memory that holds data while it moves between two parties, usually a device and a process. The device writes into the buffer at its own pace; the process reads from it at its own pace. Kernels keep buffers for disks, terminals, network cards and pipes.

The value of buffering is overlap: while the device is filling one buffer, the process can be working on data from another. How much overlap is possible depends on how many buffers there are. Take T as the time for the device to fill a block, C as the time for the process to use one, and M as the time to copy a block from the kernel buffer into the process. Stallings writes the double-buffer time as max(C, T), treating the copy as overlapped too; many course notes keep M as max(C + M, T). With M small, both give the same answer.

time to deliver one block: T = device fill 4, C = process use 3, M = copy 1no bufferingT = 4C = 37 per blocksingle buffermax(C, T) = 4M = 15 per blockdouble buffermax(C + M, T) = 44 per blockdouble buffering hides the copy: the device fills one buffer while the process drains the other
  • Single buffer: the device can read ahead one block
  • Double buffer: the copy is hidden too, so throughput approaches the slower side
  • Circular buffer: the producer–consumer bounded buffer, for bursty traffic
  • No amount of buffering helps if one side is permanently slower
3

What Is Spooling?

  1. Spool – the process writes its whole job to a file in the spool directory and continues.
  2. Queue – the spooler adds the job to a queue, usually FIFO, sometimes by priority.
  3. Drain – whenever the device is free, the spooler sends it the next complete job.
  4. Control – users and administrators can list, reorder or cancel jobs still in the queue.

Spooling (Simultaneous Peripheral Operations On-Line) uses the disk as a very large buffer for a device that can serve only one job at a time. When a process prints, its output is written to a file in a spool directory, and the call returns immediately. A background spooler daemon keeps a queue of these files and sends them to the device one complete job at a time.

The effect is that a dedicated, non-shareable device behaves as if it were shareable: every process can print at once, none waits for paper, and the jobs come out whole rather than interleaved line by line. The classic example is the print queue; batch systems also spooled card-reader input to disk before running jobs.

  • Disk-backed, so jobs survive a device failure or a reboot
  • Processes never block on the device itself
  • Jobs are never interleaved on the device
  • Costs disk space; a full spool rejects new jobs
Key reference

Terms, operations, and practical uses

Core vocabulary

  • BufferMemory holding data in transit between two parties running at different speeds.
  • Double bufferingTwo buffers that alternate between filling and emptying.
  • Spool directoryWhere whole jobs wait as files until the device takes them.
  • Spooler daemonThe background process that feeds queued jobs to the device.

Formulas

  • No bufferT + C per block.
  • Single buffermax(C, T) + M per block.
  • Double buffermax(C + M, T) per block.
  • Spooled printProcess blocks only for a disk write, not for the device.
Implementation

Print spooling with three jobs

jobs = [("A", "P1", 0, 4), ("B", "P2", 1, 2), ("C", "P3", 2, 3)]  # job, owner, arrival, pages


def spool_schedule(jobs):
    # The spooler prints whole jobs in arrival order, one page per tick.
    clock, schedule = 0, []
    for job, owner, arrive, pages in sorted(jobs, key=lambda j: j[2]):
        start = max(clock, arrive)
        clock = start + pages
        schedule.append((job, owner, arrive, start, clock))
    return schedule


schedule = spool_schedule(jobs)
print("Printer schedule (FIFO from the spool):")
for job, owner, arrive, start, end in schedule:
    print(f"  job {job} from {owner}: prints {start}-{end}")

# Without a spool, a process owns the printer until its job is out, so it is
# blocked from its request until its job ends.
blocked = {owner: end - arrive for _, owner, arrive, _, end in schedule}
print("Blocked without spooling:", *(f"{p}={t}" for p, t in blocked.items()), "total", sum(blocked.values()))
print("Blocked with spooling: 0 (a print call is a disk write)")


def per_block_time(t, c, m):
    # t: device fills a block, c: process uses a block, m: copy buffer -> process
    return t + c, max(c, t) + m, max(c + m, t)


none, single, double = per_block_time(4, 3, 1)
print(f"Time per block with T=4, C=3, M=1: no buffer {none}, single buffer {single}, double buffer {double}")
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Job {
    std::string name, owner;
    int arrive, pages, start = 0, end = 0;
};

// The spooler prints whole jobs in arrival order, one page per tick.
void spoolSchedule(std::vector<Job>& jobs) {
    std::sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.arrive < b.arrive; });
    int clock = 0;
    for (Job& j : jobs) {
        j.start = std::max(clock, j.arrive);
        j.end = clock = j.start + j.pages;
    }
}

int main() {
    std::vector<Job> jobs = {{"A", "P1", 0, 4}, {"B", "P2", 1, 2}, {"C", "P3", 2, 3}};
    spoolSchedule(jobs);

    std::cout << "Printer schedule (FIFO from the spool):\n";
    for (const Job& j : jobs) {
        std::cout << "  job " << j.name << " from " << j.owner << ": prints " << j.start << "-" << j.end << '\n';
    }

    // Without a spool, a process owns the printer until its job is out, so it
    // is blocked from its request until its job ends.
    int total = 0;
    std::cout << "Blocked without spooling:";
    for (const Job& j : jobs) {
        std::cout << ' ' << j.owner << '=' << j.end - j.arrive;
        total += j.end - j.arrive;
    }
    std::cout << " total " << total << '\n';
    std::cout << "Blocked with spooling: 0 (a print call is a disk write)\n";

    // t: device fills a block, c: process uses a block, m: copy buffer -> process
    int t = 4, c = 3, m = 1;
    std::cout << "Time per block with T=4, C=3, M=1: no buffer " << t + c << ", single buffer "
              << std::max(c, t) + m << ", double buffer " << std::max(c + m, t) << '\n';
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    static class Job {
        final String name, owner;
        final int arrive, pages;
        int start, end;

        Job(String name, String owner, int arrive, int pages) {
            this.name = name;
            this.owner = owner;
            this.arrive = arrive;
            this.pages = pages;
        }
    }

    // The spooler prints whole jobs in arrival order, one page per tick.
    static void spoolSchedule(List<Job> jobs) {
        jobs.sort(Comparator.comparingInt((Job j) -> j.arrive));
        int clock = 0;
        for (Job j : jobs) {
            j.start = Math.max(clock, j.arrive);
            j.end = clock = j.start + j.pages;
        }
    }

    public static void main(String[] args) {
        List<Job> jobs = new ArrayList<>(List.of(
                new Job("A", "P1", 0, 4), new Job("B", "P2", 1, 2), new Job("C", "P3", 2, 3)));
        spoolSchedule(jobs);

        System.out.println("Printer schedule (FIFO from the spool):");
        for (Job j : jobs) {
            System.out.println("  job " + j.name + " from " + j.owner + ": prints " + j.start + "-" + j.end);
        }

        // Without a spool, a process owns the printer until its job is out, so
        // it is blocked from its request until its job ends.
        int total = 0;
        StringBuilder sb = new StringBuilder("Blocked without spooling:");
        for (Job j : jobs) {
            sb.append(' ').append(j.owner).append('=').append(j.end - j.arrive);
            total += j.end - j.arrive;
        }
        System.out.println(sb + " total " + total);
        System.out.println("Blocked with spooling: 0 (a print call is a disk write)");

        // t: device fills a block, c: process uses a block, m: copy buffer -> process
        int t = 4, c = 3, m = 1;
        System.out.println("Time per block with T=4, C=3, M=1: no buffer " + (t + c) + ", single buffer "
                + (Math.max(c, t) + m) + ", double buffer " + Math.max(c + m, t));
    }
}
Watch it run

Step through it

Running on A: 4 pages at t = 0, B: 2 pages at t = 1, C: 3 pages at t = 2; 1 page per tick

processesP1 · job A (4 pp)not startedP2 · job B (2 pp)not startedP3 · job C (3 pp)not startedspool directory on disk (FIFO)emptyprinteridleprinter0123456789t = 0the slowest device, shared by everyone
Step 1

Three processes, one printer

A printer can only print one job at a time, and it prints about a page per tick while a process can generate a page in microseconds. Without help, each process would have to take the printer, and stay blocked until its job came out.

Output
1 / 9
4

Spooling vs Buffering

The two are easy to confuse because both put storage between a fast party and a slow one. The distinction examiners look for is what is stored and for whom: buffering holds part of one transfer so that I/O overlaps computation within a process; spooling holds whole jobs from many processes so that they can share one device.

Spooling against buffering
AspectBufferingSpooling
Storagemain memorydisk (spool directory)
Holdsa few blocks of one transferwhole jobs from many processes
OverlapsI/O with computation of the same jobI/O of one job with other jobs
Sizesmall, fixedlarge, grows with the queue
Typical devicedisk, network card, terminalprinter, batch input
Survives a crashnoyes, jobs are files
  • Buffer: memory, one transfer, one process
  • Spool: disk, whole jobs, many processes
  • A spooler usually buffers too, when it feeds the device
5

Buffering vs Caching

A cache also keeps data in faster memory, but for a different reason: to serve repeated access to the same data without going back to the slow device. A buffer may hold the only copy of data in transit; a cache always holds a copy of data that also lives elsewhere.

Operating systems often use one region for both. Linux's page cache is a cache for file reads and, for writes, a buffer: written pages sit there dirty until they are flushed to disk, which is why pulling a USB drive out without ejecting it can lose data.

  • Buffer: smooths one flow of data
  • Cache: speeds up repeated access
  • Buffered writes can be lost on a crash until they are flushed