本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
14Files, Pipes and Signals
Which words does the library’s notice board use most? One line of shell answers:
$ tr -cs 'A-Za-z' '\n' < words.txt | tr 'A-Z' 'a-z' | sort | uniq -c | sort -rn | head -6
14 the
5 is
4 on
3 room
3 returned
3 books
The first tr turns every run of non-letters into a newline, the second lowers the case, sort brings equal words together, uniq -c counts each run, sort -rn puts the largest counts first, and head keeps six lines. Six processes run at once, each reading what the one before it writes. None of the six programs contains a word about pipes: each reads its standard input and writes its standard output, and the shell arranged, before running them, that these be the ends of pipes. This chapter opens the files, descriptors and pipes underneath, builds the same pipeline in C, and ends with signals, the kernel’s way of interrupting a process.
You already know
Book 1: a file has a name and lives in a folder; a path names a file through its folders. Book 3, ch. 6: C reads and writes files through FILE * streams, with stdin, stdout and stderr open from the start. Book 3, ch. 8: the shell’s redirections < and >, its pipelines |, the permission bits of ls -l, hard links and symbolic links. Chapter 13: fork, exec, waitpid, the system call and its cost.
14.1 File descriptors
Definition 14.1 (File descriptor, open file description, offset)
A file descriptor is a small non-negative integer that a process uses to name a file it has opened; it indexes the process’s descriptor table, kept by the kernel. Each entry points to an open file description, a kernel object created by each successful open, which records the file, the access mode, and the file offset: the position where the next read or write starts. By convention descriptors 0, 1 and 2 are the standard input, output and error.
Four system calls do most of the work: open(path, flags, mode) returns the lowest free descriptor; read(fd, buf, n) copies at most bytes from the file to buf, advances the offset, and returns the number copied, 0 at end of file; write(fd, buf, n) does the reverse; close(fd) frees the descriptor.
int main(void)
{
int fd = open("notes.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
printf("open for writing gave descriptor %d\n", fd); /* 0, 1, 2 are taken */
ssize_t w = write(fd, "returned: 3 books", 17);
printf("write returned %zd\n", w);
close(fd);
fd = open("notes.txt", O_RDONLY);
printf("open for reading gave descriptor %d\n", fd); /* 3 is free again */
char buf[8];
ssize_t n;
while ((n = read(fd, buf, sizeof buf)) > 0) /* at most 8 bytes each time */
printf("read returned %zd: \"%.*s\"\n", n, (int)n, buf);
printf("read returned %zd: end of file\n", n);
close(fd);
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o fd_basics fd_basics.c -lm && ./fd_basics
open for writing gave descriptor 3
write returned 17
open for reading gave descriptor 3
read returned 8: "returned"
read returned 8: ": 3 book"
read returned 1: "s"
read returned 0: end of file
A read may return fewer bytes than asked: here the last one finds a single byte left. Every program that reads must loop until read returns 0, and must use the count it returns, never the size it asked for.
int main(void)
{
int out = open("abc.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (out < 0 || write(out, "abcdef", 6) != 6) return 1;
close(out);
int a = open("abc.txt", O_RDONLY); /* two opens: two open file descriptions */
int b = open("abc.txt", O_RDONLY);
int c = dup(a); /* a second descriptor for a's description */
show("a", a);
show("a", a);
show("b", b);
show("c = dup(a)", c);
show("a", a);
return 0;
}
dup code/bachelor-2/14-files-pipes-signals/listings/offsets.c$ gcc -std=c17 -O2 -Wall -Wextra -o offsets offsets.c -lm && ./offsets
a read 'a', offset now 1
a read 'b', offset now 2
b read 'a', offset now 1
c = dup(a) read 'c', offset now 3
a read 'd', offset now 4
a and b come from two opens: two descriptions, two offsets, so b starts again at a. c = dup(a) is a second descriptor for a’s description: reading through c moves a’s offset, and the last read through a gets d. A fork copies the descriptor table, not the descriptions, so parent and child share offsets too:
$ gcc -std=c17 -O2 -Wall -Wextra -o shared_offset shared_offset.c -lm && ./shared_offset
log.txt holds 23 bytes:
child line
parent line
offsets.c: descriptors 3 and 5 share one description, and so one offset; descriptor 4 has its own. Both descriptions lead to the same file.14.2 Buffering
Every read and write is a system call, with the cost measured in Chapter 13. Copying a file one byte at a time makes two system calls per byte.
Definition 14.2 (Buffered input and output, flush)
Buffered input and output gathers many small reads or writes of a program into few system calls, through a block of memory, the buffer, kept in the process: the C library’s FILE streams do this. To flush a buffer is to write its contents with a system call. An output stream is fully buffered (flushed when full, or at exit), line buffered (also at each newline; the default for a terminal) or unbuffered (stderr).
copy.c copies a file with read and write and a buffer of bytes given on its command line. strace -P traces only the calls that touch a given file, so it counts the reads of the input exactly:
ssize_t n;
while ((n = read(in, buf, b)) > 0) /* 0 means end of file */
if (write(out, buf, n) != n) {
perror("copy: write");
return 1;
}
if (n < 0)
perror("copy: read");
for b in 1 10 100 1000 4096 10000 65536; do
strace -qq -e trace=read -P "$PWD/in.txt" -o r.txt ./copy in.txt out.txt "$b"
echo "b = $b: $(wc -l < r.txt) reads"
done
$ gcc -O2 -o copy copy.c
$ head -c 100000 /dev/zero | tr '\0' 'x' > in.txt
$ bash reads.sh
b = 1: 100001 reads
b = 10: 10001 reads
b = 100: 1001 reads
b = 1000: 101 reads
b = 4096: 26 reads
b = 10000: 11 reads
b = 65536: 3 reads
$ cmp in.txt out.txt && echo same
same
Proposition 14.3 (Reads of a copy)
Copying a file of bytes with a buffer of bytes, by a loop that reads until read returns 0, makes reads, provided each read returns bytes when bytes remain, as reads of a regular file do.
Proof. Write with . The first reads return bytes each. If , one more read returns the last bytes. Then one read returns 0, and the loop stops. That is reads if and if , which is in both cases. ∎
With : reads for , for , and for , as counted. Time follows the count. Copying 4 MiB with buffers from 1 byte to 64 KiB:
for (long b = 1; b <= 65536; b *= 4) {
int in = open("big.txt", O_RDONLY);
int out = open("copy.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
long reads = 0;
double t0 = now_ms();
ssize_t n;
do {
n = read(in, buf, b);
reads++;
if (n > 0 && write(out, buf, n) != n) return 1;
} while (n > 0);
printf("%8ld %10ld %10.1f\n", b, reads, now_ms() - t0);
close(in), close(out);
}
FILE *f = fopen("copy.txt", "w");
double t0 = now_ms();
for (long k = 0; k < SIZE; k++)
putc(data[k], f); /* the library's buffer, one byte at a time */
fclose(f);
printf("putc, one byte at a time: %8.1f ms\n", now_ms() - t0);
putc code/bachelor-2/14-files-pipes-signals/listings/buffered_vs_raw.c$ gcc -std=c17 -O2 -Wall -Wextra -o buffered_vs_raw buffered_vs_raw.c -lm && ./buffered_vs_raw
b reads ms
1 4194305 1619.3
4 1048577 380.2
16 262145 97.9
64 65537 26.0
256 16385 6.8
1024 4097 2.6
4096 1025 1.3
16384 257 1.0
65536 65 0.9
putc, one byte at a time: 6.7 ms
putc.Each quadrupling of divides the time by about four, as long as system calls dominate; past a few KiB the curve flattens. putc writes one byte at a time too, but into the library’s buffer, which reaches the kernel in blocks of 4096 bytes: some two hundred times faster than one write per byte. It is still slower than write with , by the cost of four million calls to putc itself.
The buffer lives in the process, and fork copies the process. A line that waits in a buffer at the moment of a fork is then in two buffers, and both are flushed:
int main(void)
{
printf("printed once, before the fork\n"); /* stays in the buffer: not a terminal */
if (fork() == 0)
return 0; /* the child's exit flushes its copy */
wait(NULL);
return 0; /* the parent's exit flushes the original */
}
$ gcc -std=c17 -O2 -Wall -Wextra -o fork_buffer fork_buffer.c -lm && ./fork_buffer
printed once, before the fork
printed once, before the fork
On a terminal the line would be flushed at its newline, before the fork, and appear once. The cure is a fflush(stdout) before every fork, as minish did.
14.3 Names, inodes and links
Definition 14.4 (Inode, link count)
An inode is the record a file system keeps for one file: its type, size, owner, permission bits, times, and where its bytes are stored, but not its name. Its link count is the number of directory entries that name it. stat(path, &st) copies an inode’s fields into a struct stat.
Definition 14.5 (Directory entry)
A directory is a file whose contents is a table of directory entries, each a pair of a name and an inode number. A hard link is a second entry for an existing inode; a symbolic link is a small file whose contents is a path.
So a file has no name of its own: names belong to directories. Removing a name (unlink, which rm calls) removes one entry and lowers the link count; the file disappears when the count reaches 0 and no process has it open.
$ echo 'opens at nine' > hours.txt
$ ln hours.txt opening.txt
$ ln -s hours.txt shortcut.txt
$ ls -l
total 8
-rw-r--r-- 2 ada ada 14 Jan 5 2026 hours.txt
-rw-r--r-- 2 ada ada 14 Jan 5 2026 opening.txt
lrwxrwxrwx 1 ada ada 9 Jan 5 2026 shortcut.txt -> hours.txt
$ rm hours.txt
$ cat opening.txt
opens at nine
$ cat shortcut.txt
cat: shortcut.txt: No such file or directory
$ ls -l
total 4
-rw-r--r-- 1 ada ada 14 Jan 5 2026 opening.txt
lrwxrwxrwx 1 ada ada 9 Jan 5 2026 shortcut.txt -> hours.txt
The second column of ls -l is the link count: 2 for hours.txt and opening.txt, one inode under two names. After rm hours.txt, opening.txt still reads the text, while shortcut.txt, which stores the path hours.txt, leads nowhere. The same in C, with stat comparing inode numbers (which the program never prints):
if (link("first.txt", "second.txt") != 0) /* a second directory entry */
return 1;
struct stat s1, s2;
stat("first.txt", &s1);
stat("second.txt", &s2);
int same = s1.st_ino == s2.st_ino && s1.st_dev == s2.st_dev;
printf("same inode: %s\n", same ? "yes" : "no");
printf("link count: %ld, size: %ld bytes\n", (long)s1.st_nlink, (long)s1.st_size);
unlink("first.txt"); /* remove one name */
stat("second.txt", &s2);
printf("after unlink: link count %ld, the file is still there\n", (long)s2.st_nlink);
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o same_inode same_inode.c -lm && ./same_inode
same inode: yes
link count: 2, size: 9 bytes
after unlink: link count 1, the file is still there
hours.txt, looked up by name each time it is used, so removing the name hours.txt breaks it but not opening.txt.14.4 Redirections and pipes
Definition 14.6 (Descriptor duplication)
Duplicating a descriptor makes a second descriptor point to the same open file description: dup(fd) uses the lowest free number, and dup2(fd, target) uses target, closing first whatever it pointed to.
That is the whole of a redirection. For echo hello > out.txt, the shell forks; the child opens out.txt, makes descriptor 1 point to it with dup2, closes the extra descriptor and execs echo, which writes to descriptor 1 as always. Since an exec keeps the descriptor table, echo never knows.
pid_t r = fork();
if (r == 0) {
int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
dup2(fd, 1); /* descriptor 1 now means out.txt */
close(fd); /* the copy in 1 is enough */
execlp("echo", "echo", "hello", (char *)NULL);
_exit(127);
}
> out.txt code/bachelor-2/14-files-pipes-signals/listings/redirect.c$ gcc -std=c17 -O2 -Wall -Wextra -o redirect redirect.c -lm && ./redirect
out.txt: hello
echo wrote.Definition 14.7 (Pipe)
A pipe is a kernel buffer with two ends, created by pipe(fd): bytes written to the write end fd[1] are read, in the same order, from the read end fd[0]. A read on an empty pipe waits; a write to a full pipe waits; on Linux a pipe holds 65 536 bytes, and a write of at most 4096 bytes is never mixed with another writer’s. A read returns 0, end of file, when the pipe is empty and no write end is open anywhere.
Proposition 14.8 (End of file on a pipe)
A process reading an empty pipe sees end of file exactly when every descriptor referring to the pipe’s write end, in every process, has been closed. While one remains open, even in the reader itself, the read waits.
The proof is Exercise 14.8. The consequence is a rule: after a fork, every process must close every pipe end it does not use. A parent that forgets its copy of the write end leaves the reader waiting forever:
}
close(fd[0]);
if (write(fd[1], "twelve bytes", 12) != 12) return 1;
printf("parent: wrote 12 bytes, now waiting for wc\n");
fflush(stdout);
/* close(fd[1]); <- the missing line */
waitpid(r, NULL, 0); /* wc waits for end of file: forever */
printf("parent: never printed\n");
$ gcc -std=c17 -O2 -Wall -Wextra -o forgot_close forgot_close.c -lm && ./forgot_close
parent: wrote 12 bytes, now waiting for wc
[killed after 3 s]
[exit status -9]
wc never prints; the capture tool stopped the program after 3 seconds.Method 14.9 (Building a pipeline)
To run commands connected by pipes, for in order:
- if , create pipe ;
- fork; in the child, if ,
dup2the read end of pipe onto 0; if ,dup2the write end of pipe onto 1; close every pipe descriptor it still holds; exec command ; - in the parent, close the read end of pipe and the write end of pipe , keeping only the read end of pipe for the next child.
Then wait for the children; the pipeline’s status is the last command’s.
int run_pipeline(char **const stages[], int k) /* returns the last stage's status */
{
int prev = -1; /* read end of the previous pipe */
pid_t last = -1;
for (int i = 0; i < k; i++) {
int fd[2] = {-1, -1};
if (i < k - 1 && pipe(fd) != 0)
return 1;
pid_t r = fork();
if (r == 0) {
if (prev != -1) { /* standard input from the previous stage */
dup2(prev, 0);
close(prev);
}
if (fd[1] != -1) { /* standard output into the next pipe */
dup2(fd[1], 1);
close(fd[1]);
close(fd[0]);
}
execvp(stages[i][0], stages[i]);
perror(stages[i][0]);
_exit(127);
}
if (prev != -1)
close(prev); /* the parent keeps no end it does not use */
if (fd[1] != -1)
close(fd[1]);
prev = fd[0];
last = r;
}
int status = 0, s;
pid_t w;
while ((w = wait(&s)) > 0) /* every stage, in any order */
if (w == last)
status = WIFEXITED(s) ? WEXITSTATUS(s) : 128 + WTERMSIG(s);
return status;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o pipeline pipeline.c pipeline_lib.c -lm && ./pipeline
14 the
5 is
4 on
3 room
3 returned
3 books
6 processes, 5 pipes; the last stage exited with 0
pipeline.c.14.5 Signals
Definition 14.10 (Signal, handler, disposition)
A signal is a small numbered notification that the kernel delivers to a process, interrupting whatever it was doing: on a key (SIGINT, 2, for Ctrl-C), on an event (SIGCHLD, 17, a child ended; SIGPIPE, 13, a write to a pipe with no reader), or because another process called kill(pid, sig) (SIGTERM, 15, “please end”; SIGKILL, 9, “end now”). The disposition of a signal in a process says what delivery does: the default action (for most signals, end the process; for SIGCHLD, nothing), ignore it, or call a function of the process, a signal handler, installed with sigaction. SIGKILL and SIGSTOP cannot be caught or ignored. The numbers are those of Linux on x86-64.
static void on_sigint(int sig)
{
(void)sig;
interrupted = 1; /* only set a flag: see the text */
}
struct sigaction sa = {0};
sa.sa_handler = on_sigint;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL); /* from now on, SIGINT calls on_sigint */
kill(getpid(), SIGINT); /* as if Ctrl-C were typed */
printf("handled: interrupted = %d, and the program goes on\n", (int)interrupted);
$ gcc -std=c17 -O2 -Wall -Wextra -o sigint_self sigint_self.c -lm && ./sigint_self
default: child killed by signal 2
handled: interrupted = 1, and the program goes on
A handler runs in the middle of the program, between two instructions of whatever main was doing, perhaps inside printf with the buffer half updated. If the handler called printf too, the two uses of the same buffer would mix.
Definition 14.11 (Async-signal-safe function)
A function is async-signal-safe when it can be called safely from within a signal handler. POSIX lists them: write, _exit, waitpid and most plain system calls are; printf, malloc and anything that takes a lock or touches a shared buffer are not.
The safe pattern is the one above: the handler sets a variable of type volatile sig_atomic_t, and the main program looks at it. The commonest real handler reaps children, so that a program that starts many does not collect zombies:
static void on_sigchld(int sig)
{
(void)sig;
int saved = errno; /* waitpid may change errno */
while (waitpid(-1, NULL, WNOHANG) > 0) /* several children may have ended */
reaped++;
errno = saved;
}
sigset_t block, old;
sigemptyset(&block);
sigaddset(&block, SIGCHLD);
sigprocmask(SIG_BLOCK, &block, &old); /* no signal between test and sleep */
for (int k = 0; k < 5; k++)
if (fork() == 0)
_exit(k);
while (reaped < 5)
sigsuspend(&old); /* unblock, sleep until a signal */
sigprocmask(SIG_SETMASK, &old, NULL);
printf("5 children started, %d reaped by the handler, no zombie left\n", (int)reaped);
return 0;
$ gcc -std=c17 -O2 -Wall -Wextra -o sigchld_reap sigchld_reap.c -lm && ./sigchld_reap
5 children started, 5 reaped by the handler, no zombie left
Two details matter. Signals of one kind do not queue: five children ending at once may produce a single SIGCHLD, so the handler loops on waitpid(-1, NULL, WNOHANG), which reaps one ended child per call and returns 0 when none is left. And between the test reaped < 5 and going to sleep, the last signal could arrive and be missed: blocking SIGCHLD and sleeping with sigsuspend, which unblocks and sleeps in one step, closes that window.
The last signal of the chapter ends pipelines early. When head has printed its lines and exits, the stages before it are still writing into a pipe that nobody reads:
static void writer(int ignore)
{
int fd[2];
if (pipe(fd) != 0) _exit(1);
close(fd[0]); /* no reader left */
if (ignore)
signal(SIGPIPE, SIG_IGN);
ssize_t n = write(fd[1], "x", 1);
printf("write returned %zd, errno %s\n", n, n < 0 ? strerror(errno) : "-");
fflush(stdout);
_exit(0);
}
$ gcc -std=c17 -O2 -Wall -Wextra -o sigpipe sigpipe.c -lm && ./sigpipe
SIGPIPE default: the writer was killed by signal 13
write returned -1, errno Broken pipe
SIGPIPE ignored: the writer went on and exited normally
SIGPIPE kills the writer; ignored, it turns into an error.That is why yes | head -3 ends: yes would write forever, but its first write after head has exited kills it with SIGPIPE, silently.
In practice — Descriptors in servers
Every long-running program has the bugs of this chapter in waiting. A server that forgets to close descriptors runs out of them after some thousands of connections (a process may hold a limited number); one that forks without reaping fills the process table with zombies; one that writes to a client who has gone away dies of SIGPIPE unless it ignores the signal and checks every write. The usual practice: ignore SIGPIPE in servers, check the result of every call, close every descriptor on every path, and reap every child.
14.6 Exercises
Exercise 14.1 ★
A file holds the 26 letters a to z. A program reads it with read(fd, buf, 10) until end of file. What does each call return, and what is in buf after the last call that returned bytes? What changes if the program calls lseek(fd, 20, SEEK_SET) first?
Solution
Solution of Exercise 14.1.
The calls return 10, 10, 6 and 0: the offset goes 0, 10, 20, 26, and the fourth read finds nothing left. The third read copies uvwxyz into the first six bytes of buf and leaves the other four as the second read left them, so buf holds uvwxyzqrst: only the first 6 bytes, the count read returned, are data. After lseek(fd, 20, SEEK_SET) the offset starts at 20: one read returns 6, uvwxyz, and the next 0.
Exercise 14.2 ★
In forgot_close.c, the parent never closes fd[1]. Say which processes hold a descriptor of the write end when wc reads, and where to add the missing close. Would closing it after waitpid work?
Solution
Solution of Exercise 14.2.
The child duplicates fd[0] onto 0 and closes both fd[0] and fd[1] before its exec, so wc holds no write end. The parent closes fd[0] but keeps fd[1]: it is the only holder, and by Proposition 14.8 wc waits as long as it is open. The missing close(fd[1]) goes right after the write, before waitpid. After waitpid it is too late: the parent waits for wc, which waits for end of file, which waits for the parent’s close. Each waits for the other, forever.
Exercise 14.3 ★
Write mycp src dst [b], which copies with a buffer of bytes (4096 by default), gives the copy the same permission bits as the source, never overwrites an existing file, and handles a write that writes fewer bytes than asked.
Solution
Solution of Exercise 14.3.
/* O_EXCL: the open fails if dst exists, so nothing is ever overwritten */
int out = open(argv[2], O_WRONLY | O_CREAT | O_EXCL, st.st_mode & 07777);
char *buf = malloc(b);
if (out < 0 || !buf) {
perror("mycp: destination");
return 1;
}
ssize_t n;
while ((n = read(in, buf, b)) > 0) {
for (ssize_t done = 0; done < n;) { /* write may write less than asked */
ssize_t w = write(out, buf + done, n - done);
if (w < 0 && errno != EINTR) {
perror("mycp: write");
return 1;
}
done += w > 0 ? w : 0;
}
}
fchmod(out, st.st_mode & 07777); /* the umask may have cleared some bits */
close(in);
return close(out) != 0 || n < 0;
fstat reads the source’s inode, so the mode is the source’s. O_EXCL with O_CREAT makes open fail if the destination exists, in the same system call that would create it, so no other program can create it in between. The mode passed to open is reduced by the process’s umask, which usually clears the write bits of the group and others, so fchmod sets the bits exactly at the end. The inner loop writes again until the n bytes read are all written, since a write may write fewer. The test copies 70 000 bytes of mode 751 with , 7, 4096 and 100 000, and checks that a second copy to the same name fails.
Exercise 14.4 ★
How many write calls does copy.c make for bytes and a buffer of ? How many system calls in all, counting the opens and closes? For , which brings the total under 300?
Solution
Solution of Exercise 14.4.
One write for each read that returned bytes: . With the reads of Proposition 14.3, two opens and two closes, the total is (the loader’s own calls before main, about thirty, come on top). For , the total is under 300 when , that is , so : gives 299 calls, while gives 148 writes and 301.
Exercise 14.5 ★★
What does this program print when its output is a file? When it is a terminal? Explain.
int main(void)
{
printf("A");
pid_t r = fork();
printf("B\n");
if (r > 0)
wait(NULL);
return 0;
}
printf without newline code/bachelor-2/14-files-pipes-signals/listings/exo_nonewline.cSolution
Solution of Exercise 14.5.
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_nonewline exo_nonewline.c -lm && ./exo_nonewline
AB
AB
A.Into a file, the output is fully buffered: A waits in the buffer, fork copies it, each process appends B and a newline, and each flushes AB at exit. On a terminal the output is line buffered, but a line is flushed at its newline and A has none, so it is still in the buffer at the fork: the terminal shows AB twice as well. The newline matters, not the terminal. fflush(stdout) before fork prints A, then B twice.
Exercise 14.6 ★★
This redirection swaps the arguments of dup2. Explain the output, and what dup2(1, fd) did.
if (fork() == 0) {
int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
dup2(1, fd); /* meant: dup2(fd, 1) */
close(fd);
execlp("echo", "echo", "meant for out.txt", (char *)NULL);
_exit(127);
}
wait(NULL);
struct stat st;
stat("out.txt", &st);
printf("out.txt has %ld bytes\n", (long)st.st_size);
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_swapped exo_swapped.c -lm && ./exo_swapped
meant for out.txt
out.txt has 0 bytes
Solution
Solution of Exercise 14.6.
dup2(1, fd) makes fd point to the description of descriptor 1, the terminal or the capture file, and closes what fd pointed to: out.txt’s only description, so the file stays as open left it, created and truncated. close(fd) then removes the extra copy of descriptor 1, and echo writes to 1 as always: the text goes to the parent’s output, and out.txt has 0 bytes. Read dup2(old, new) as “make new a copy of old”.
Exercise 14.7 ★★
Write tee [-a] file..., which copies its standard input to its standard output and to every file named, truncating them, or appending with -a.
Solution
Solution of Exercise 14.7.
int first = 1, flags = O_WRONLY | O_CREAT | O_TRUNC;
if (argc > 1 && strcmp(argv[1], "-a") == 0) {
flags = O_WRONLY | O_CREAT | O_APPEND; /* every write goes to the end */
first = 2;
}
int fds[MAXFILES + 1] = {1}, k = 1, bad = 0;
for (int i = first; i < argc && k <= MAXFILES; i++) {
int fd = open(argv[i], flags, 0644);
if (fd < 0) {
perror(argv[i]);
bad = 1;
} else {
fds[k++] = fd;
}
}
char buf[4096];
ssize_t n;
while ((n = read(0, buf, sizeof buf)) > 0)
for (int i = 0; i < k; i++)
if (write_all(fds[i], buf, n) != 0)
bad = 1;
for (int i = 1; i < k; i++)
close(fds[i]);
return bad || n < 0;
tee: one read, several writes code/bachelor-2/14-files-pipes-signals/exercises/tee.cDescriptor 1 is placed first in the table of outputs, so the loop treats it like the files. O_APPEND makes the kernel move the offset to the end before each write, which is what -a asks even if another program writes the file meanwhile. A file that cannot be opened is reported and skipped; the others are still written, and the status says something failed. write_all loops as in mycp. The test sends 18 000 bytes through two files, then appends a line with -a.
Exercise 14.8 ★★
Prove Proposition 14.8 from the definition of a pipe. Deduce that in Method 14.9, if every command reads its input to the end before it exits, the last command sees end of file only after all the others have ended.
Solution
Solution of Exercise 14.8.
Suppose the pipe is empty. By the definition of a pipe, a read on it returns 0 when no write end is open anywhere, which is the “if” direction. Conversely, while some process holds an open descriptor of the write end, that process may still write: the kernel cannot know that no byte will come, so the read waits, and returns 0 only once the last such descriptor is closed (by close, by dup2 over it, or by the process’s end, which closes all its descriptors). Closing a descriptor of the read end changes nothing, and neither does a reader’s copy of the write end being “its own”: it counts like any other.
In the method, pipe ’s write end is created in the parent, inherited by child , and closed by the parent right after that fork, before child exists; child moves it to descriptor 1 and closes the original. So the only descriptor of pipe ’s write end is child ’s descriptor 1, and child sees end of file exactly when child has ended (or closed its output). By induction on : child 1 ends at some moment; child 2 sees end of file only after that, and, reading to the end before exiting, ends only after that; and so on to child , which sees end of file only after children have all ended.
Exercise 14.9 ★★
Write capture(argv, input, &status), which runs a command with the string input as its standard input and returns, as a new string, everything it printed. Why does a version that first writes all the input and then reads the output hang when the input is 300 000 bytes and the command is cat?
Solution
Solution of Exercise 14.9.
pid_t cmd = fork();
if (cmd == 0) { /* stdin from to, stdout into from */
dup2(to[0], 0);
dup2(from[1], 1);
close(to[0]), close(to[1]), close(from[0]), close(from[1]);
execvp(argv[0], argv);
_exit(127);
}
pid_t feeder = fork();
if (feeder == 0) { /* a second child writes the input */
close(to[0]), close(from[0]), close(from[1]);
size_t n = strlen(input);
_exit(write(to[1], input, n) == (ssize_t)n ? 0 : 1);
}
close(to[0]), close(to[1]), close(from[1]); /* or the command never sees end of file */
The function grows its result while it reads. The naive version hangs because two pipes are full at once. cat copies its input to its output; nobody reads the output yet, so after 64 KiB that pipe is full and cat waits in write, and stops reading. Then the input pipe fills with the next 64 KiB, and the parent waits in its own write. Neither moves again. With 300 000 bytes, more than the two pipes and cat’s buffer hold, it happens every time; with a few KiB, never. The cure is to write and read at the same time: here a second child writes the input while the parent reads the output. The parent must close its copy of to[1], or the command never sees end of file; the feeder ends after its write, closing the last copy. The test checks cat, a status of 3, and the 300 000 bytes.
Exercise 14.10 ★★★
Add <, > and | to the shell of Chapter 13, as separate words: sort < in.txt > out.txt, echo 3 1 2 | wc -w. In which order must the child apply the pipes and the redirections, so that a > f | b sends a’s output to f?
Solution
Solution of Exercise 14.10.
static void redirect(char **w) /* in a child: apply and remove < f, > f */
{
int j = 0;
for (int i = 0; w[i]; i++) {
int in = strcmp(w[i], "<") == 0, out = strcmp(w[i], ">") == 0;
if ((in || out) && w[i + 1]) {
int fd = in ? open(w[i + 1], O_RDONLY)
: open(w[i + 1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror(w[i + 1]);
_exit(1);
}
dup2(fd, in ? 0 : 1);
close(fd);
i++; /* skip the file name */
} else {
w[j++] = w[i];
}
}
w[j] = NULL;
}
pid_t pids[MAXW];
int prev = -1;
for (int i = 0; i < k; i++) {
int fd[2] = {-1, -1};
if (i < k - 1 && pipe(fd) != 0)
return 1;
if ((pids[i] = fork()) == 0) {
sigset_t none; /* the shell's mask would outlive exec */
sigemptyset(&none);
sigprocmask(SIG_SETMASK, &none, NULL);
signal(SIGCHLD, SIG_DFL);
if (prev != -1) dup2(prev, 0), close(prev);
if (fd[1] != -1) dup2(fd[1], 1), close(fd[1]), close(fd[0]);
redirect(stage[i]); /* after the pipes: > f wins over | */
if (!stage[i][0]) _exit(0);
execvp(stage[i][0], stage[i]);
fprintf(stderr, "minish2: %s: command not found\n", stage[i][0]);
_exit(127);
}
if (prev != -1) close(prev);
if (fd[1] != -1) close(fd[1]);
prev = fd[0];
}
The line is cut at each | into stages, wired by Method 14.9. Each child first installs its pipe ends, then applies its redirections, which remove themselves from the words before the exec. In that order a > replaces the pipe on descriptor 1, so a > f | b writes a’s output to f, and b reads an empty pipe: end of file as soon as a ends. That is also what a real shell does. In the other order the pipe would overwrite the redirection. The test runs a redirected sort, a three-stage pipeline, and false | true.
Exercise 14.11 ★★★
Fit the model to the measurements of Output 14.6, where is the cost of one read and its write and the cost of moving one byte. Compare with the cost of a system call measured in Chapter 13, and find the beyond which the system calls cost less than the bytes.
Solution
Solution of Exercise 14.11.
# least squares on relative errors: minimise the sum of ((a x + c N - t) / t)^2
s = [[0.0, 0.0], [0.0, 0.0]]
r = [0.0, 0.0]
for _, x, t in rows:
u, v = x / t, N / t
s[0][0] += u * u
s[0][1] += u * v
s[1][1] += v * v
r[0] += u
r[1] += v
det = s[0][0] * s[1][1] - s[0][1] ** 2
a = (r[0] * s[1][1] - r[1] * s[0][1]) / det
c = (r[1] * s[0][0] - r[0] * s[0][1]) / det
print(f"a = {a * 1e6:.0f} ns per read and write, c = {c * 1e6:.3f} ns per byte")
for b, x, t in rows:
print(f"b = {b:>5}: measured {t:7.1f} ms, model {a * x + c * N:7.1f} ms")
$ python fit_copy.py
a = 375 ns per read and write, c = 0.215 ns per byte
b = 1: measured 1619.3 ms, model 1574.5 ms
b = 4: measured 380.2 ms, model 394.3 ms
b = 16: measured 97.9 ms, model 99.3 ms
b = 64: measured 26.0 ms, model 25.5 ms
b = 256: measured 6.8 ms, model 7.0 ms
b = 1024: measured 2.6 ms, model 2.4 ms
b = 4096: measured 1.3 ms, model 1.3 ms
b = 16384: measured 1.0 ms, model 1.0 ms
b = 65536: measured 0.9 ms, model 0.9 ms
The model is linear in and ; the script uses the read counts of the measurement and minimises the relative errors, so that the fast rows count as much as the slow ones. On this run ns for one read and its write, and ns per byte; the model is within about 10 % of every row. A read and a write are two system calls, about 190 ns each: more than the 70 ns of the empty call of Chapter 13, because each finds the file, checks the offset and copies data. The two terms are equal when , that is bytes. Beyond about 2 KiB the bytes cost more than the calls, which is where the curve of the chapter flattens.
Exercise 14.12 ★★★
Add background jobs to the shell of Exercise 14.10: a line ending with the word & is not waited for, a SIGCHLD handler reaps the processes that end, and the next prompt reports how many ended. How do you keep the handler from reaping a foreground process before the shell’s waitpid?
Solution
Solution of Exercise 14.12.
for (;;) {
if (finished != reported) { /* report at the prompt, not in a handler */
printf("[done: %d background process%s]\n", finished - reported,
finished - reported == 1 ? "" : "es");
reported = finished;
}
printf("minish2$ ");
fflush(stdout);
if (!fgets(line, sizeof line, stdin))
break;
int n = 0;
for (char *t = strtok(line, " \t\n"); t && n < MAXW; t = strtok(NULL, " \t\n"))
w[n++] = t;
w[n] = NULL;
int background = n > 0 && strcmp(w[n - 1], "&") == 0;
if (background)
w[--n] = NULL;
if (n == 0)
continue;
if (strcmp(w[0], "exit") == 0)
return last;
if (strcmp(w[0], "cd") == 0) {
last = chdir(n > 1 ? w[1] : "/") != 0;
continue;
}
sigprocmask(SIG_BLOCK, &chld, &old); /* the handler waits until we have waited */
last = run_line(w, n, background);
sigprocmask(SIG_SETMASK, &old, NULL);
}
return last;
The handler is that of sigchld_reap.c: it reaps every ended child with WNOHANG and counts them, and the main loop, never the handler, prints the report before the next prompt. A background line is wired as any other and not waited for. The danger is the handler’s waitpid(-1, ...) reaping a foreground child before the shell’s own waitpid, which would then fail and lose the status. Two measures prevent it: SIGCHLD is blocked from before the forks until the foreground stages are reaped, and the shell waits for its own PIDs only, never for any child. When the mask is restored, the pending signal runs the handler, which finds only background processes left. A child inherits the blocked mask, and an exec keeps it, so each child unblocks SIGCHLD before its exec. The test runs sleep 0.2 &, then sleep 0.6, and expects one report.
14.7 Problem: The word-frequency pipeline in C
Problem 14.1
Weekend problem — The word-frequency pipeline in C
The problem follows the hook’s pipeline through the kernel: its descriptors, its processes and pipes, its buffers, and its end.
Part I — Descriptors.
- In
pipeline.c, which descriptor doesopen("words.txt", ...)return, and why that one? - After
dup2(in, 0)andclose(in), what does descriptor 0 refer to? Which process will read it? - In Output 14.2, why does the second
openreturn 3 again? - Using Output 14.3, explain why the parent’s line lands after the child’s in
shared_offset.c. - What would
shared_offset.cproduce if the child openedlog.txtitself, after the fork? - Which inode fields does
ls -lshow in Output 14.8?
Part II — Six processes and five pipes.
- List, for each of the six children of
pipeline.c, its descriptors 0 and 1 just before its exec. - How many pipe descriptors does the parent hold, at most, at any moment? Prove it from the code.
- Which child sees end of file first, and when? Use Proposition 14.8.
- Why can
sortprint nothing before it has read all its input, whiletrprints as it reads? - Suppose the parent kept every read end until the end. Which stage would then never finish, if any?
- The pipeline’s status is
head’s. Give a pipeline whose status hides a failure, and say how a shell could report it.
Part III — Buffering measured.
- State Proposition 14.3 and check it on every line of Output 14.5.
- How many reads would and give? ? ?
- In Output 14.6, compare the ratio of the times for and with the ratio of the read counts.
- Why does the time stop falling beyond a few KiB?
trreads its input with a buffer of the library. Estimate its number of reads onwords.txt, 440 bytes, if the buffer is 4096 bytes.- Why is
putc, one byte at a time, so much faster thanwritewith ? Why is it still slower than ?
Part IV — An early end.
head -6exits after six lines. What happens tosort -rn’s next write if it has more to write?- Use Output 14.15 to say how
sortends in that case, and what status it has. - Why does the shell not print an error message for that death?
- A program ignores
SIGPIPEand does not check whatwritereturns. What does it do afterheadhas exited? - Here, with a 440-byte text, does
sort -rnactually receiveSIGPIPE? Use the pipe’s capacity. - State the buffer-size law, with the counts it predicts from to .
Solution
Solution of Problem 14.1.
1. 3: open returns the lowest free descriptor, and 0, 1 and 2 are the standard streams, open since the program started.
2. The open file description of words.txt, at offset 0; 3 is free again. Every child inherits it, but children 2 to 6 put a pipe over their descriptor 0, so only the first, tr -cs, reads it.
3. close freed 3, which is again the lowest free descriptor.
4. The fork copies the descriptor table, not the description: parent and child share one offset. The child’s 11 bytes move it to 11, and the parent, which waited, writes its 12 bytes from there: 23 bytes, child first.
5. The child would have a description of its own, at offset 0, and the parent’s would stay at 0 too. The child writes its 11 bytes at 0, then the parent writes its 12 bytes at 0 over them: the file holds parent line and its newline, 12 bytes.
6. The type and the permission bits (-rw-r--r--, or l for the link), the link count, the owner and group, the size, and the time of the last modification of the contents. The name comes from the directory, and the -> hours.txt from the symbolic link’s contents.
7. Child 1, tr -cs: 0 is words.txt, 1 the write end of pipe 1. Child for to 5: 0 is the read end of pipe , 1 the write end of pipe . Child 6, head: 0 is the read end of pipe 5, and 1 is the parent’s standard output.
8. Three. At the start of iteration the parent holds one, prev; pipe adds two, the fork copies them all to the child, and then the parent closes prev and fd[1], keeping only fd[0]. So it holds three from the pipe to the closes, and one between iterations; after the last iteration, none.
9. tr -cs, reading a regular file: its read returns 0 after the 440 bytes. Among the pipe readers, child 2 is first: its end of file comes when child 1 ends, since child 1 holds the only write end of pipe 1.
10. The last line of the input may be the first line of the output, so sort can write nothing before end of file. tr translates each byte on its own and writes as soon as its buffer is full.
11. None: end of file depends only on write ends. But if head stopped early with more data on the way, the stage before it would not die of SIGPIPE, since a read end would still be open in the parent. It would fill the pipe and wait in write forever. With this small text no stage blocks, but in general one would.
12. false | true has status 0, and grep word missing.txt | sort has status 0 though the file does not exist. A shell can collect every stage’s status, as run_pipeline’s loop does before it keeps only the last, and return the first that is not 0. Some shells offer this as an option (pipefail).
13. With : , ; , ; , ; , ; , ; , ; , . Each count matches.
14. : . : . : . : also 2.
15. On the run printed, , while the read counts give . At small the time is almost exactly the number of system calls times a constant.
16. Past a few KiB the calls are few: 1025 reads and writes at , about 0.4 ms at the 375 ns of Exercise 14.11. The time left is the moving of the 4 MiB from the kernel to the buffer and back, the term, which no buffer size reduces.
17. By Proposition 14.3 with and : reads, one returning the 440 bytes and one returning 0.
18. putc is a function call that stores a byte in the library’s buffer, a few nanoseconds; the system call comes once per 4096 bytes, 1024 times for 4 MiB. That is the same number of writes as the copy with ; what remains is four million calls to putc, which the raw copy does not make.
19. Pipe 5’s read end is closed in every process (head has exited, and the parent closed its copy), so the write raises SIGPIPE in sort.
20. By default SIGPIPE kills the writer: sort ends by signal 13, which run_pipeline records as , then ignores, since only head’s status is the pipeline’s.
21. Death by SIGPIPE is the normal end of a writer whose reader has stopped wanting more, as with yes | head -3; a shell that reported it would print a message under most pipelines ending in head. And the dead stage’s status is not the pipeline’s anyway.
22. Every later write fails at once with EPIPE. Not checking, the program goes on computing and writing into nothing, until its work runs out; a program like yes would never stop.
23. No. sort -rn writes only after its input has ended, and its output, a few hundred bytes, leaves its buffer in one write at exit. The pipe holds 65 536 bytes, so that write succeeds at once, whether or not head has yet read anything; head has not exited before it, since it waits for its first read. No write happens after head’s exit.
24. The buffer-size law: a copy of bytes with a buffer of bytes makes reads. For it predicts, from to , 100 001, 10 001, 1001, 101, 26, 11 and 3 reads, the seven counts of Output 14.5.