Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 18 (Nov 05), slide deck
system-io. Reading: CS:APP3e chapter 10. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (macOS). Unix I/O is a kernel service, so there is nothing architecture-specific to cross-compile. Code:code/lecture18/. Reading time: ~85 minutes; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Use the Unix I/O calls —
open,read,write,close,lseek— and explain the “everything is a file” uniformity they give. - Explain short counts: why
readmay transfer fewer bytes than requested, and write a RIO-style loop that cannot lose data. - Draw the three tables (descriptor table, open file table, v-node table) and predict what
fork,dupand a secondopendo to the file position. - Read file metadata with
statand test file type with theS_IS*macros. - Implement I/O redirection with
dup2, and explain how a shell’s>works without the redirected program’s cooperation. - Explain standard I/O buffering, why mixing
printfandwritereorders output, why an unflushed buffer is duplicated byfork, and when to choose Unix I/O over standard I/O.
0.2 Prerequisites and scope
- Lecture 16:
fork/exec/wait. Redirection is what the shell does between the fork and the exec, so Lectures 16 + 18 together are a working shell. - Lecture 17: signals.
EINTR— “a signal interrupted this call” — is a case every robust I/O loop must handle. - Lectures 11–12: the kernel’s data structures live in its own address space;
stat, descriptors and the open-file table are the programmer-visible part. - In scope: CS:APP chapter 10 — Unix I/O, short counts and RIO, metadata, descriptor sharing, redirection, standard I/O and the trade-offs.
- Out of scope: sockets (Lectures 19–20 use this lecture’s RIO package on them) and the file system’s on-disk layout (Lecture 19).
0.3 Section → code map
| Section | Idea | Demo in code/lecture18/ |
|---|---|---|
| §1–§2 | open/read/write/close/lseek, stat | 01_unix_io.c |
| §3 | short counts and the RIO loop | 02_short_counts.c, rio.c |
| §4 | the three tables; fork/dup sharing a position | 03_descriptors.c |
| §5 | redirection with dup2 | 04_redirect.c |
| §6 | standard I/O buffering surprises | 05_buffering.c |
1. Unix I/O: one interface for everything
A Unix file is just a sequence of bytes. That is the entire model — no records, no structure, no types the kernel cares about. And the kernel applies it to everything: regular files, directories, pipes, sockets, terminals, disks, even kernel state (/proc on Linux). Consequently all I/O is done with the same small set of calls, and a program that reads a file can read a network connection without changing a line.
The calls:
| Call | What it does |
|---|---|
open(path, flags, mode) | Ask the kernel for access to a file; returns a descriptor |
read(fd, buf, n) | Copy up to n bytes from the file into buf; returns how many |
write(fd, buf, n) | Copy up to n bytes from buf into the file; returns how many |
close(fd) | Release the descriptor |
lseek(fd, off, whence) | Move the current file position without transferring data |
A file descriptor is a small non-negative integer: an index into a per-process table. Every process starts with three already open, by convention:
0 = STDIN_FILENO 1 = STDOUT_FILENO 2 = STDERR_FILENO
open always returns the lowest unused descriptor, which is why the first file you open is reliably 3. 01_unix_io.c confirms it:
[fds] stdin=0 stdout=1 stderr=2 (always open at startup)
[open] 'build/01_data.txt' for writing -> fd=3 (lowest unused descriptor)
That “lowest unused” rule sounds like an implementation detail. It is actually the mechanism redirection is built on (§5).
1.1 Flags, mode, and the file position
open’s flags say how you want access: O_RDONLY / O_WRONLY / O_RDWR, plus optional O_CREAT (create if missing), O_TRUNC (discard existing contents), O_APPEND (every write goes to the end). The mode (e.g. 0644 = rw-r--r--) sets permissions, and matters only when the file is actually created.
Each descriptor carries a file position: the byte offset where the next read or write will happen. read and write advance it by the number of bytes transferred; lseek sets it directly (SEEK_SET from the start, SEEK_CUR relative, SEEK_END from the end) and moves no data. From the demo, on a 29-byte file:
[read] first 8 bytes: "line one"
[lseek] position after reading 8 bytes: 8
[lseek] after seeking to byte 9, next 8 bytes: "line two"
[lseek] last 6 bytes (from offset 23): "three\n"
Byte 9 is the start of the second line ("line one\n" is 9 bytes), and the last 6 bytes begin at 29 − 6 = 23. Where that position is stored turns out to be the subtle part — §4.
2. Metadata: stat
The bytes are the file’s contents; the kernel also keeps metadata about the file — size, type, permissions, owner, timestamps, link count. stat(path, &st) (or fstat(fd, &st)) copies it into a struct stat:
[stat] size=29 bytes regular file=yes dir=no mode=644
Test the type with the macros rather than comparing bits by hand: S_ISREG (regular file), S_ISDIR (directory), S_ISFIFO, S_ISSOCK, S_ISLNK. This is how ls -l gets everything it prints, and how a web server decides whether a URL names a file to send or a directory to list (Lecture 20).
Crucially, metadata belongs to the file, not to your descriptor — two processes with the file open see one size.
3. Short counts, and the RIO package
3.1 Why read returns less than you asked for
read(fd, buf, 1000) may return 100. This is a short count, and it is not an error. The kernel gives you what is available now rather than making you wait for data that may never come. Short counts happen when:
- you reach EOF (the last block of a file is short — then the next call returns 0);
- you read from a pipe, socket or terminal and the sender has not finished;
- a signal interrupted the call part-way (Lecture 17).
On disk files you barely notice, which is exactly the trap: code that ignores short counts passes every local test and then loses data the moment it reads a network connection. 02_short_counts.c reproduces it on one machine with a pipe whose writer trickles 100 bytes every 20 ms:
[a] asked read() for 1000 bytes, got 100 <-- a SHORT count
[a] the remaining 900 bytes arrived in later read() calls
[a] total 1000; a program that trusted the first read would have
silently lost 900 bytes
[b] asked rio_readn() for 1000 bytes, got 1000 <-- COMPLETE
[c] read() on a pipe with no writer returned 0 (0 = EOF)
Learn the three return values as three different facts:
| Return | Meaning |
|---|---|
> 0 | this many bytes moved — possibly fewer than requested |
= 0 | EOF: the stream is over, no more data will ever come |
< 0 | a real error — check errno; EINTR means “interrupted, just retry” |
3.2 The RIO package
The fix is always the same loop, so it is packaged once. rio.c provides two families:
- Unbuffered:
rio_readn(fd, buf, n)andrio_writen(fd, buf, n)transfer exactlynbytes, looping over short counts and retrying onEINTR.rio_readnreturns less thannonly at EOF. Use them for binary blocks of known length. - Buffered:
rio_readinitb(&rio, fd)thenrio_readlineb/rio_readnb. These keep an internal 8 KB buffer, so reading a text line costs one syscall per ~8 KB instead of one per character. Essential for line-oriented protocols like HTTP (Lecture 20).
The core of rio_readn is worth reading closely, because the loop is the lesson:
while (nleft > 0) {
ssize_t nread = read(fd, bufp, nleft);
if (nread < 0) {
if (errno == EINTR) continue; /* a signal, not a failure: retry */
return -1; /* a genuine error */
}
if (nread == 0) break; /* EOF -> short count */
nleft -= nread; /* believe the kernel */
bufp += nread;
}
The buffered reader may be mixed with rio_readnb on the same stream — read HTTP headers line by line, then the body as a block — because both draw from the same buffer. Mixing raw read with the buffered reader, by contrast, loses whatever is already buffered.
4. How descriptors really work: three tables
A descriptor is not “the file”. The kernel keeps three levels, and knowing which fact lives where answers almost every puzzling I/O question:
descriptor table open file table v-node table
(one per PROCESS) (one per OPEN, shareable) (one per FILE)
fd 0 ──┐
fd 1 ──┼──────────────────▶ { file POSITION, refcnt } ──▶ { size, type, perms }
fd 2 ──┘
fd 3 ─────────────────────▶ { file POSITION, refcnt } ──▶ { … }
- The descriptor table is private to your process:
fd→ an open-file entry. - The open file table is shared kernel-wide, one entry per
open. The file position lives here, with a reference count. - The v-node table holds one entry per actual file: the metadata
statreports.
Three consequences, all demonstrated by 03_descriptors.c on a file containing 0123456789ABCDEFGHIJ:
(1) Two opens of one file ⇒ two positions. Separate open calls create separate open-file entries, so they read independently:
[1] two separate open() calls: fd1=3 fd2=4
fd1 reads 5 bytes: "01234"
fd2 reads 5 bytes: "01234" <-- starts at 0 again
(2) fork ⇒ one shared position. The child gets a copy of the descriptor table, but both copies point at the same open-file entry, bumping its refcount. So the child’s reads move the parent’s position:
[2] one open() then fork(): fd=3 in both processes
child reads 5 bytes: "01234"
parent reads 5 bytes: "56789" <-- continues after the child
shared position is now 10 (not 5)
The parent read bytes 5–9, not 0–4. (wait() before the parent’s read makes this deterministic instead of a race.) This sharing is a feature: it is why prog >> log from a parent and its children interleaves into the log sensibly instead of overwriting.
(3) dup adds a reference; close removes one. dup(fd) returns a new descriptor for the same open-file entry, so the two share a position — and closing one leaves the other fully usable:
[3] dup(): fd 3 and fd 4 share one open-file entry
fd 3 reads 3: "012"
fd 4 reads 3: "345" <-- shared position, continues
after close(3), fd 4 still reads 3: "678"
So close does not “close the file”; it drops a reference. The entry is freed when the count reaches zero. That is also why forgetting to close descriptors leaks them: a long-running server that opens without closing eventually exhausts its descriptor table.
5. I/O redirection: dup2
printf writes to descriptor 1. It has no idea whether descriptor 1 is a terminal, a file or a pipe — and that ignorance is what makes redirection possible. To run ls > out.txt the shell does not modify ls. It forks, and in the child, before execve, it points descriptor 1 at the file:
int fd = open("out.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
dup2(fd, STDOUT_FILENO); /* descriptor 1 now refers to out.txt */
execve("/bin/ls", argv, environ);
dup2(old, new) makes new a copy of old, closing whatever new referred to first. Because the redirected program only ever writes to “descriptor 1”, it cannot tell the difference and needs no cooperation.
04_redirect.c does this to its own stdout and then reads the file back to prove where the text went:
[1] this line goes to the terminal (fd 1 = your screen)
[4] stdout restored: this line is on the terminal again
[file] 'build/04_redirected.txt' now contains 61 bytes:
| [2] this line goes into the file
| [3] ...and so does this one
Lines [2] and [3] never reached the terminal. Note the two practical details: save the old stdout with dup first if you want it back (because dup2 closes it), and fflush before swapping, or buffered text will be written to the new destination (§6). Pipes (|) work the same way, with pipe() providing the two descriptors and dup2 wiring one process’s stdout to the other’s stdin.
6. Standard I/O: buffering, and when it bites
6.1 Two layers
printf/fopen/fgets are standard I/O: a C library layer above Unix I/O. A FILE is a descriptor plus a buffer. printf appends to that buffer in your own address space and calls write only later — when the buffer fills, when a '\n' is printed to a terminal, when you call fflush, or at exit. write has no buffer and goes to the kernel immediately.
Buffering mode depends on the destination:
- to a terminal: line-buffered (flushed at each newline);
- to a file or pipe: fully buffered (held until ~8 KB or exit).
That difference is why a program’s output can change the moment you redirect it — the classic “it only misbehaves in the log file” bug.
6.2 Two surprises, measured
05_buffering.c captures both in a file so you can see the result:
(a) Ordering. Source order is printf("A"), write(1,"B",1), printf("C"). Output:
[a] the file actually contains: "BAC"
B went straight to the kernel while A and C sat in the stdio buffer until the flush. Never interleave printf and write on one descriptor without flushing between them.
(b) fork duplicates the buffer. One printf("X"), not flushed, then a fork; both processes flush at exit:
[b] the file actually contains: "XX" (2 characters)
One printf, two X’s. The fixes: fflush(stdout) before fork (so there is nothing to duplicate), and _exit rather than exit in a child (so inherited buffers are not flushed again) — the same advice Lecture 16 gave for fork.
This is not a hypothetical. While writing this lecture, demo
03printed its first two sections twice undermake run. The reason was exactly (b):makepipes the output, so stdio was fully buffered, and theforkcopied everything printed so far. Adding onefflush(stdout)before theforkfixed it. On a terminal the bug is invisible — line buffering had already flushed each line. See the code README’s “Plan vs reality”.
6.3 Which should you use?
| Use | When |
|---|---|
| Standard I/O | ordinary files and terminal output; formatted text; you want convenience and buffering for free |
| RIO / Unix I/O | sockets and pipes; when you must handle short counts explicitly; inside signal handlers (write is async-signal-safe, printf is not) |
The reasons to avoid standard I/O on a network connection are concrete: a socket is read and written through one descriptor, and standard I/O’s rules for interleaving reads and writes on one stream are restrictive and easy to violate; its buffering also makes it hard to know when bytes actually left. CS:APP’s recommendation, which these notes follow in Lectures 19–20: use RIO on sockets.
Summary
- Unix models every file as a sequence of bytes and exposes all of them through
open/read/write/close/lseek. A descriptor is an index into a per-process table; 0/1/2 are stdin/stdout/stderr, andopenreturns the lowest unused one. statreports metadata (size, type, permissions) that belongs to the file, not the descriptor; test types withS_ISREG/S_ISDIR/…- A short count —
readreturning fewer bytes than requested — is normal on pipes, sockets and at EOF. Distinguish>0(partial),0(EOF) and<0(error, withEINTRmeaning retry). RIO wraps the loop:rio_readn/rio_writenfor exact blocks,rio_readlinebfor text lines. - Three tables: descriptor (per process) → open file (per
open, holds the file position and a refcount) → v-node (per file, the metadata). Hence twoopens read independently,forkanddupshare one position, andclosedrops a reference. dup2implements redirection by pointing a descriptor somewhere else; the redirected program cannot tell. Shell>,<and|arefork+dup2+exec.- Standard I/O buffers in user space: mixing
printfwithwritereorders output, and an unflushed buffer is duplicated byfork. Prefer RIO on sockets, andwritein signal handlers.
Common pitfalls
- Trusting one
read. Always loop (or userio_readn); a singlereadis correct only if you genuinely accept partial data. - Treating
EINTRas failure. It means a signal arrived before any data moved — retry the call. - Confusing 0 with an error.
readreturning 0 is EOF;-1is the error. - Assuming a child’s reads do not affect you. After
fork, the file position is shared; use a secondopenif you want an independent one. - Forgetting that
dup2closes its target. Save the old descriptor withdupfirst if you need it back. - Mixing
printfandwrite, or forking with a dirty buffer.fflushfirst; use_exitin children. - Using standard I/O on a socket. Use RIO; a socket is bidirectional on one descriptor and standard I/O’s interleaving rules make that fragile.
- Leaking descriptors.
closewhat youopen; a server that does not will run out of table entries.
Exercises
-
Which descriptor? A process has stdin/stdout/stderr open, then calls
openthree times. What descriptors come back, and what if it had closed stdin first?Answer
3, 4, 5 — the lowest unused each time. Had it closed stdin (descriptor 0) first, the next `open` would return **0**, because 0 is then the lowest unused slot. That is precisely the mechanism `dup2`-based redirection exploits. -
Short count. You call
read(sockfd, buf, 4096)on a socket and it returns 1. Is this an error? What must your code do?Answer
Not an error — only one byte had arrived. The code must loop, accumulating until it has as much as the protocol requires (or `read` returns 0 for EOF). `rio_readn` does exactly this; a program that assumed 4096 would silently mis-parse the stream. -
Shared position. A process opens a file, reads 10 bytes, then forks. The child reads 10 bytes and exits; the parent (after
wait) reads 10. Which bytes does the parent get, and why?Answer
Bytes **20–29**. The position lives in the open file table, and `fork` makes both descriptor tables point at the same entry, so the child's read advanced the shared position from 10 to 20. (With a second `open` instead of a `fork`, the parent would have read 10–19 from its own position.) -
Two opens. Same scenario, but instead of forking, the process
opens the same file a second time and reads 10 bytes from the new descriptor. Which bytes?Answer
Bytes **0–9**. A second `open` creates a second open-file entry with its own position starting at 0. Independent opens do not share a position; only `fork` and `dup` do. -
Redirection. Write the three calls a shell makes in the child to implement
cmd 2> errs.txt(redirect stderr).Answer
`int fd = open("errs.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);` then `dup2(fd, STDERR_FILENO);` then `close(fd);` — and then `execve` the command. Descriptor 2 now refers to the file; the command writes errors there without knowing. -
The reordering. Explain why
printf("A"); write(1,"B",1); printf("C");can produceBAC, and give two different one-line fixes.Answer
`printf` appends `A` and `C` to the stdio buffer in user space; `write` sends `B` to the kernel immediately. The buffer is flushed later (at exit), so `B` lands first. Fixes: call `fflush(stdout)` before the `write`; or use `write` for all three; or (third option) `setvbuf` the stream unbuffered. -
One printf, two lines. A program
printfs a line with no trailing newline, then forks; both processes exit normally. Redirected to a file, the text appears twice, but on a terminal only once. Why both facts?Answer
To a file, stdout is fully buffered, so the text was still in the buffer at `fork` time and was duplicated; each process flushed its copy at `exit`. On a terminal stdout is line-buffered — but with **no newline** it would also be buffered, so the one-copy terminal case is usually because the text *did* end in a newline and was flushed before the fork. The robust fix either way: `fflush(stdout)` before forking, and `_exit` in the child.
The related lab
This lecture’s content underlies the shell lab (redirection with dup2, descriptors across fork/exec) and is a prerequisite for the proxy lab (where every socket read must tolerate short counts). The RIO package here is the same idea as the one the labs provide. Per the course’s academic-integrity policy these notes contain no lab solutions: the demos show each mechanism in isolation, with no shell, no job control, and no proxy.
Further reading
- CS:APP3e chapter 10 in full; §10.4 (RIO), §10.6 (descriptor sharing and redirection) and §10.9 (Unix vs standard I/O) match demos 02, 03/04 and 05.
man 2 open,man 2 read,man 2 dup2,man 2 stat— the authoritative semantics, including every flag and the completestruct stat.- The Linux Programming Interface (Kerrisk), chapters 4–5 and 13 — the deepest practical treatment of descriptors, buffering and the three tables.
Preview of Lecture 19: File systems and network programming I
So far a “file” has been an abstraction. Lecture 19 opens it up: how a file system stores files on a disk (superblock, inodes, data blocks, directories) and how a path like /home/me/notes.txt is looked up one component at a time — built as a small, runnable toy file system. Then it turns outward: the Internet as a hierarchy of networks, IP addresses, DNS names, and the socket as the endpoint of a connection — preparing the full sockets interface in Lecture 20.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| system-level I/O | 系统级 I/O |
| Unix I/O | Unix I/O |
| file descriptor | 文件描述符 |
stdin / stdout / stderr | 标准输入 / 标准输出 / 标准错误 |
open / close | 打开 / 关闭 |
read / write | 读 / 写 |
lseek | 移动文件位置 |
| file position / offset | 文件位置 / 偏移量 |
flags (O_RDONLY, O_CREAT, O_TRUNC, O_APPEND) | 打开标志 |
| mode / permissions | 权限位 |
| metadata | 元数据 |
stat / fstat | 获取文件元数据 |
| regular file / directory | 普通文件 / 目录 |
| short count | 不足计数(短读/短写) |
| EOF (end of file) | 文件结束 |
EINTR | 被信号中断 |
| robust I/O (RIO) | 健壮 I/O |
| buffered reader | 带缓冲读取器 |
| descriptor table | 描述符表 |
| open file table | 打开文件表 |
| v-node table | v-node 表 |
| reference count | 引用计数 |
dup / dup2 | 复制描述符 |
| I/O redirection | I/O 重定向 |
| pipe | 管道 |
| standard I/O | 标准 I/O(C 库) |
| buffering (line / full / unbuffered) | 缓冲(行 / 全 / 无) |
fflush | 刷新缓冲区 |
| async-signal-safe | 异步信号安全 |