← Runtimes
Runtimes

System calls and the kernel boundary

See which library calls actually reach the kernel.

System calls carry requests from a program’s libraries into the operating-system kernel.

Outcome

Explain how a program crosses into the kernel, predict how many system calls a library call makes in each language, and read data whose pieces do not line up with its records.

Terminology (7)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Kernel
The part of the operating system that runs with full hardware privileges and manages memory, devices, files and processes.
System call
A request from a program to the kernel, made by a special instruction that switches the CPU into kernel mode and back.
User space
Where programs and their libraries run, without direct access to devices or other processes’ memory.
Buffer
Memory in the program where a library collects bytes, so one system call can carry many small writes or serve many small reads.
Flush
Ask a buffered writer to pass pending bytes to its underlying destination. It may require several writes or report an error.
Short read
A read that returns fewer bytes than requested without being at end of file.
/proc/self/io
A Linux file exposing aggregate process I/O counters, including syscr and syscw for file-read and file-write call families. Waited-for child activity is included.

Requests across the kernel boundary

Programs run in user space. To open a file, write bytes or start a process, the program asks the kernel with a system call: a special CPU instruction that switches into kernel mode, runs the kernel’s handler and returns a result, often a byte count or an error number.

You rarely make system calls directly. Standard libraries wrap them. One library call may make several system calls (reading a whole file opens it, checks its size, reads, and closes), exactly one, or none at all when the library can answer from its own memory.

01The kernel boundary

A library call is not a system call

An audit exporter must preserve every access record while reducing repeated calls into the operating system. Its short-line file writes cross into the kernel one by one, yet nearby progress output can stay in a library buffer. To change the exporter safely, first determine what those library calls actually send and when.

Typical Linux system calls behind familiar operations
Library operationSystem calls
Read a whole fileopenat, fstat, read … read (0 bytes), close
Write to an unbuffered handlewrite-family calls; retries can add calls
Write to a buffered streamnone until the buffer fills or is flushed, then write
Format or sort already available datano I/O call required; allocation/runtime work can still enter the kernel

02Count the calls

Measure the export’s I/O calls

Before choosing a buffer, test the assumption that one library call means one kernel request. Linux’s /proc/self/io exposes read-family and write-family call counts, including other I/O in the same process. This probe reads a 100,000-byte file, then prints three lines to a pipe on the runner. It calibrates the counter reader’s own overhead and reports the differences on stderr. The table after the prediction is a dated observation, not a portable count guarantee.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { readFileSync, writeFileSync } from 'node:fs';

/** System calls this process has made so far, as counted by Linux in /proc/self/io. */
function systemCalls(kind: 'syscr' | 'syscw'): number {
  const match = new RegExp(`${kind}:\\s*(\\d+)`).exec(readFileSync('/proc/self/io', 'utf8'));
  return Number(match![1]);
}

writeFileSync('/tmp/big.txt', 'x'.repeat(100_000));

const overhead = -systemCalls('syscr') + systemCalls('syscr');
const readsBefore = systemCalls('syscr');
const text = readFileSync('/tmp/big.txt', 'utf8');
const reads = systemCalls('syscr') - readsBefore - overhead;

const writesBefore = systemCalls('syscw');
console.log('one');
console.log('two');
console.log('three');
const writes = systemCalls('syscw') - writesBefore;

console.error(`read ${text.length} bytes with ${reads} read calls`);
console.error(`3 print calls made ${writes} write calls`);
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
In the recorded Linux runner setup, stdout is a pipe. Predict the observed write-call difference for the three short prints between counter readings. The reveal reports that run, not a portable API guarantee.

03Buffered or not

Which handles collect bytes before the kernel sees them

Now choose where to batch the audit records. A file handle opened by the standard library is not automatically buffered. The handle or wrapper determines whether successive small writes collect in user-space memory. For this bounded export, fewer write calls are the goal; the file content must remain unchanged.

A loop successfully writes 1,000 nonempty lines to a regular file with fs.writeSync(fd, line) once per line. Assume no explicit extra flushes. What can you conclude about write system calls?

04Reads return pieces

The kernel does not know where your records end

With the export’s bytes intact, the audit reader needs to count records marked DENY. It reads at most 64 bytes per call to keep each transfer small. That maximum is not a record size: a long user name can move the action field across a read boundary. A successful positive-size read on this regular file returns bytes or 0 at EOF; errors are a separate result. Nonblocking descriptors can also report would-block rather than waiting.

A program reads a file containing exactly HELLO followed by a newline, calling read with room for 64 bytes each time. Which sequence of results can it receive?

05Practice

Export and audit with a call budget

The lab continues the exporter: write the exact records, batch its small fixture export within two kernel write-family calls, then retain record state across 64-byte reads. The fixtures use LF-terminated user,ACTION lines with ASCII user identifiers containing no comma and actions ALLOW or DENY. They are a bounded audit format, not a general CSV parser. Linux counters measure the call differences; supplied chunk-reader coverage checks the helper’s byte limit and complete traversal separately.

The audit export

An exporter writes access records to a file and reads them back, with Linux counting every read and write system call. Write the export, fit it into a two-call budget, then count denied records while reading 64 bytes at a time.

  1. easy · R-SYS-V4-1 Write the export
  2. medium · R-SYS-V4-2 Fit the write budget
  3. hard · R-SYS-V4-3 Count across reads
Check this idea later
A C++ service prints progress with printf, and its output is redirected to a log file. It crashes after printing three lines. What can the log file contain?
A Go job writes 50,000 log lines with fmt.Fprintln to an *os.File and is slow. What change reduces the number of system calls?
A client reads from a TCP stream socket with a 4 KB buffer, expecting each read to return one complete JSON message. Under load, some messages fail to parse. Why?
Sources
In the frontend An HTTP stream chunk is another boundary, not a system call. Optional

The audit dashboard can receive newline-delimited records from a streaming endpoint. A server enqueue, a kernel write and one browser reader.read result are different boundaries. Keep the record delimiter meaningful while allowing the transport to split or combine chunks. This endpoint deliberately splits one record between enqueues; a browser must not assume that each received chunk is a complete record.

app/api/audit/route.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export function GET() {
  const encoder = new TextEncoder();
  const body = new ReadableStream({
    start(controller) {
      controller.enqueue(encoder.encode('ann,AL'));
      controller.enqueue(encoder.encode('LOW\nbo,DENY\n'));
      controller.close();
    }
  });

  return new Response(body, {
    headers: { 'Content-Type': 'text/plain; charset=utf-8' }
  });
}

An App Router Route Handler can return a Web Response backed by a ReadableStream. These two enqueue calls describe application chunks, not two Linux writes or two network packets. A fetch client can collect the whole body with response.text(), or keep unfinished records while reading the body stream.

Sources: Next.js: Route Handlers,SvelteKit: server routes,Web API: ReadableStream reader results.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.