计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本: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
Output 14.1. Six programs, five pipes: the six most frequent words of a short text.

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 nn 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;
}
Listing 14.1. Writing a file, then reading it 8 bytes at a time code/bachelor-2/14-files-pipes-signals/listings/fd_basics.c
$ 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
Output 14.2. The descriptor is 3 both times; the reads return 8, 8, 1, then 0.

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;
}
Listing 14.2. Two opens, and one 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
Output 14.3. Who shares an offset with whom.

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
Output 14.4. The parent writes after the child’s line, not over it.
The three levels after 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.
The three levels after 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 bb 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");
Listing 14.3. The copying loop code/bachelor-2/14-files-pipes-signals/listings/copy.c
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
Listing 14.4. Counting the reads for seven buffer sizes code/bachelor-2/14-files-pipes-signals/listings/reads.sh
$ 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
Output 14.5. A file of 100 000 bytes, copied with seven buffer sizes.

Proposition 14.3 (Reads of a copy)

Copying a file of nn bytes with a buffer of bb bytes, by a loop that reads until read returns 0, makes ⌈n/b⌉+1\lceil n / b \rceil + 1 reads, provided each read returns min⁡(b,r)\min(b, r) bytes when rr bytes remain, as reads of a regular file do.

Proof. Write n=qb+rn = qb + r with 0≤r<b0 \le r < b. The first qq reads return bb bytes each. If r>0r > 0, one more read returns the last rr bytes. Then one read returns 0, and the loop stops. That is q+1+1q + 1 + 1 reads if r>0r > 0 and q+1q + 1 if r=0r = 0, which is ⌈n/b⌉+1\lceil n/b \rceil + 1 in both cases. ∎

With n=100 000n = 100\,000: 100 001100\,001 reads for b=1b = 1, ⌈100 000/4096⌉+1=26\lceil 100\,000 / 4096 \rceil + 1 = 26 for b=4096b = 4096, and 2+1=32 + 1 = 3 for b=65 536b = 65\,536, 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);
Listing 14.5. The timed loop, and the same copy by 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
Output 14.6. One run on the author’s laptop: 4 MiB copied with nine buffer sizes, then written by putc.
The times of . Up to about 1 KiB the line falls with slope -1: the time is the number of system calls. Beyond, the cost of moving the bytes themselves dominates, and a larger buffer gains little.
The times of Output 14.6. Up to about 1 KiB the line falls with slope −1-1: the time is the number of system calls. Beyond, the cost of moving the bytes themselves dominates, and a larger buffer gains little.

Each quadrupling of bb 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 b=4096b = 4096, 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 */
}
Listing 14.6. A line printed once code/bachelor-2/14-files-pipes-signals/listings/fork_buffer.c
$ 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
Output 14.7. It appears twice, because the output is not a terminal.

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.

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;
}
Listing 14.7. Two names, one inode code/bachelor-2/14-files-pipes-signals/listings/same_inode.c
$ 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
Output 14.9. The link count goes from 2 to 1.
A directory as a table of names. Two entries lead to inode A; the symbolic link’s inode B holds the path hours.txt, looked up by name each time it is used, so removing the name hours.txt breaks it but not opening.txt.
A directory as a table of names. Two entries lead to inode A; the symbolic link’s inode B holds the path 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);
    }
Listing 14.8. The child’s side of > 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
Output 14.10. What 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");
Listing 14.9. The parent keeps the write end code/bachelor-2/14-files-pipes-signals/listings/forgot_close.c
$ 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]
Output 14.11. wc never prints; the capture tool stopped the program after 3 seconds.

Method 14.9 (Building a pipeline)

To run kk commands connected by k−1k - 1 pipes, for i=1,…,ki = 1, \dots, k in order:

  1. if i<ki < k, create pipe ii;
  2. fork; in the child, if i>1i > 1, dup2 the read end of pipe i−1i - 1 onto 0; if i<ki < k, dup2 the write end of pipe ii onto 1; close every pipe descriptor it still holds; exec command ii;
  3. in the parent, close the read end of pipe i−1i - 1 and the write end of pipe ii, keeping only the read end of pipe ii for the next child.

Then wait for the kk 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;
}
Listing 14.10. The method in C: the parent holds at most one pipe end between forks code/bachelor-2/14-files-pipes-signals/listings/pipeline_lib.c
$ 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
Output 14.12. The hook’s six stages, connected by pipeline.c.
A pipe before and after the wiring. Right after the fork, both processes hold both ends. Each then keeps one: the writer’s descriptor 1 and the reader’s descriptor 0 become the ends, and every other copy is closed, so that the reader sees end of file when the writer is done.
A pipe before and after the wiring. Right after the fork, both processes hold both ends. Each then keeps one: the writer’s descriptor 1 and the reader’s descriptor 0 become the ends, and every other copy is closed, so that the reader sees end of file when the writer is done.

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 */
}
Listing 14.11. A handler sets a flag, and nothing more code/bachelor-2/14-files-pipes-signals/listings/sigint_self.c
    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);
Listing 14.12. Installing it code/bachelor-2/14-files-pipes-signals/listings/sigint_self.c
$ 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
Output 14.13. The default action, then the handler.

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;
}
Listing 14.13. Reaping in the handler: every ended child, without waiting code/bachelor-2/14-files-pipes-signals/listings/sigchld_reap.c
    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;
Listing 14.14. Waiting for the signals without missing one code/bachelor-2/14-files-pipes-signals/listings/sigchld_reap.c
$ 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
Output 14.14. Five children, five reaped.

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.

A signal’s delivery. Sent, it is pending until the kernel next returns to the process in user mode; the handler then runs on the process’s stack, and when it returns the program goes on as if nothing had happened, except what the handler changed.
A signal’s delivery. Sent, it is pending until the kernel next returns to the process in user mode; the handler then runs on the process’s stack, and when it returns the program goes on as if nothing had happened, except what the handler changed.

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);
}
Listing 14.15. Writing into a pipe whose read end is closed code/bachelor-2/14-files-pipes-signals/listings/sigpipe.c
$ 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
Output 14.15. By default 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 bb 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;
Copying with the source’s permission bits code/bachelor-2/14-files-pipes-signals/exercises/mycp.c

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 b=1b = 1, 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 nn bytes and a buffer of bb? How many system calls in all, counting the opens and closes? For n=106n = 10^6, which bb brings the total under 300?

Solution

Solution of Exercise 14.4.

One write for each read that returned bytes: ⌈n/b⌉\lceil n / b \rceil. With the ⌈n/b⌉+1\lceil n/b \rceil + 1 reads of Proposition 14.3, two opens and two closes, the total is 2⌈n/b⌉+52\lceil n/b \rceil + 5 (the loader’s own calls before main, about thirty, come on top). For n=106n = 10^6, the total is under 300 when ⌈106/b⌉≤147\lceil 10^6 / b \rceil \le 147, that is b≥106/147b \ge 10^6 / 147, so b≥6803b \ge 6803: ⌈106/6803⌉=147\lceil 10^6 / 6803 \rceil = 147 gives 299 calls, while b=6802b = 6802 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;
}
Listing 14.16. A printf without newline code/bachelor-2/14-files-pipes-signals/listings/exo_nonewline.c
Solution

Solution of Exercise 14.5.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_nonewline exo_nonewline.c -lm && ./exo_nonewline
AB
AB
Output 14.17. Two lines, both with the 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);
Listing 14.17. The child’s side, then the parent’s check code/bachelor-2/14-files-pipes-signals/listings/exo_swapped.c
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_swapped exo_swapped.c -lm && ./exo_swapped
meant for out.txt
out.txt has 0 bytes
Output 14.16. The text went to the wrong place.
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.c

Descriptor 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 ii’s write end is created in the parent, inherited by child ii, and closed by the parent right after that fork, before child i+1i + 1 exists; child ii moves it to descriptor 1 and closes the original. So the only descriptor of pipe ii’s write end is child ii’s descriptor 1, and child i+1i + 1 sees end of file exactly when child ii has ended (or closed its output). By induction on ii: 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 kk, which sees end of file only after children 1,…,k−11, \dots, k-1 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 */
Two children: the command, and one that feeds it code/bachelor-2/14-files-pipes-signals/exercises/capture_cmd.c

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;
}
Applying and removing the redirections, in the child code/bachelor-2/14-files-pipes-signals/exercises/minish2.c
    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];
    }
Cutting the line into stages and wiring them code/bachelor-2/14-files-pipes-signals/exercises/minish2.c

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 t=a⌈n/b⌉+c nt = a \lceil n/b \rceil + c\,n to the measurements of Output 14.6, where aa is the cost of one read and its write and cc the cost of moving one byte. Compare aa with the cost of a system call measured in Chapter 13, and find the bb 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")
Least squares on relative errors code/bachelor-2/14-files-pipes-signals/listings/fit_copy.py
$ 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
Output 14.18. The fit, on one run of the author’s laptop.

The model is linear in aa and cc; 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 a≈375a \approx 375 ns for one read and its write, and c≈0.2c \approx 0.2 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 a n/b=c na\,n/b = c\,n, that is b=a/c≈375/0.215≈1700b = a / c \approx 375 / 0.215 \approx 1700 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 prompt reports; the handler reaps code/bachelor-2/14-files-pipes-signals/exercises/minish2.c

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.

  1. In pipeline.c, which descriptor does open("words.txt", ...) return, and why that one?
  2. After dup2(in, 0) and close(in), what does descriptor 0 refer to? Which process will read it?
  3. In Output 14.2, why does the second open return 3 again?
  4. Using Output 14.3, explain why the parent’s line lands after the child’s in shared_offset.c.
  5. What would shared_offset.c produce if the child opened log.txt itself, after the fork?
  6. Which inode fields does ls -l show in Output 14.8?

Part II — Six processes and five pipes.

  1. List, for each of the six children of pipeline.c, its descriptors 0 and 1 just before its exec.
  2. How many pipe descriptors does the parent hold, at most, at any moment? Prove it from the code.
  3. Which child sees end of file first, and when? Use Proposition 14.8.
  4. Why can sort print nothing before it has read all its input, while tr prints as it reads?
  5. Suppose the parent kept every read end until the end. Which stage would then never finish, if any?
  6. 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.

  1. State Proposition 14.3 and check it on every line of Output 14.5.
  2. How many reads would b=3b = 3 and b=99 999b = 99\,999 give? b=100 000b = 100\,000? b=100 001b = 100\,001?
  3. In Output 14.6, compare the ratio of the times for b=1b = 1 and b=4b = 4 with the ratio of the read counts.
  4. Why does the time stop falling beyond a few KiB?
  5. tr reads its input with a buffer of the library. Estimate its number of reads on words.txt, 440 bytes, if the buffer is 4096 bytes.
  6. Why is putc, one byte at a time, so much faster than write with b=1b = 1? Why is it still slower than b=4096b = 4096?

Part IV — An early end.

  1. head -6 exits after six lines. What happens to sort -rn’s next write if it has more to write?
  2. Use Output 14.15 to say how sort ends in that case, and what status it has.
  3. Why does the shell not print an error message for that death?
  4. A program ignores SIGPIPE and does not check what write returns. What does it do after head has exited?
  5. Here, with a 440-byte text, does sort -rn actually receive SIGPIPE? Use the pipe’s capacity.
  6. State the buffer-size law, with the counts it predicts from b=1b = 1 to b=65 536b = 65\,536.
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 ii for i=2i = 2 to 5: 0 is the read end of pipe i−1i - 1, 1 the write end of pipe ii. 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 ii 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 n=100 000n = 100\,000: b=1b = 1, 100 000+1100\,000 + 1; b=10b = 10, 10 000+110\,000 + 1; b=100b = 100, 1000+11000 + 1; b=1000b = 1000, 100+1100 + 1; b=4096b = 4096, ⌈24.4⌉+1=26\lceil 24.4 \rceil + 1 = 26; b=10 000b = 10\,000, 10+110 + 1; b=65 536b = 65\,536, ⌈1.53⌉+1=3\lceil 1.53 \rceil + 1 = 3. Each count matches.

14. b=3b = 3: ⌈33 333.3⌉+1=33 335\lceil 33\,333.3 \rceil + 1 = 33\,335. b=99 999b = 99\,999: 2+1=32 + 1 = 3. b=100 000b = 100\,000: 1+1=21 + 1 = 2. b=100 001b = 100\,001: also 2.

15. On the run printed, 1619.3/380.2≈4.31619.3 / 380.2 \approx 4.3, while the read counts give 4 194 305/1 048 577≈4.04\,194\,305 / 1\,048\,577 \approx 4.0. At small bb 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 b=4096b = 4096, 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 c nc\,n term, which no buffer size reduces.

17. By Proposition 14.3 with n=440n = 440 and b=4096b = 4096: ⌈0.107⌉+1=2\lceil 0.107 \rceil + 1 = 2 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 b=4096b = 4096; 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 128+13=141128 + 13 = 141, 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 nn bytes with a buffer of bb bytes makes ⌈n/b⌉+1\lceil n/b \rceil + 1 reads. For n=100 000n = 100\,000 it predicts, from b=1b = 1 to b=65 536b = 65\,536, 100 001, 10 001, 1001, 101, 26, 11 and 3 reads, the seven counts of Output 14.5.

本章定义的术语

在术语表中查看全部 1050 个术语