CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 3 min read

The pipe

In plain words: A pipe is like a short length of garden hose. Water poured in one end comes out of the other, in the same order, and nothing runs back. The analogy stops at one point: a hose spills when it is too full, and a pipe makes the writer wait instead.

The call pipe(fd) creates a pipe and fills a two-element array with two file descriptors: fd[0] is the read end and fd[1] is the write end. Bytes written to fd[1] can be read from fd[0], in order. The data is held in a buffer inside the kernel, not in a file on disk.

A pipe connects two processes only because of fork. The child receives a copy of both descriptors (page 3), so parent and child hold both ends. Each side then closes the end it does not use.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
    int fd[2];
    if (pipe(fd) != 0) { perror("pipe"); return 1; }
    pid_t pid = fork();
    if (pid == 0) {
        close(fd[0]);                               /* child writes only */
        const char *msg = "hello through a pipe\n";
        if (write(fd[1], msg, 21) != 21) _exit(1);
        close(fd[1]);
        _exit(0);
    }
    close(fd[1]);                                   /* parent reads only */
    char buf[64];
    ssize_t n = read(fd[0], buf, sizeof buf - 1);
    buf[n] = '\0';
    printf("parent read %zd bytes: %s", n, buf);
    n = read(fd[0], buf, sizeof buf);
    printf("second read returned %zd (end of file)\n", n);
    wait(NULL);
    return 0;
}

Output:

parent read 21 bytes: hello through a pipe
second read returned 0 (end of file)

The message has 21 bytes: 20 letters and spaces plus the newline. A read on an empty pipe waits until data arrives. When every copy of the write end has been closed and the pipe is empty, read returns 0, which means end of file. That is how the reader learns that the writer is done.

This is also why unused ends must be closed. If the parent had kept its own copy of fd[1] open, the second read would never return 0, because a writer would still exist, and the parent would wait for ever.

Pipe

A pipe is a one-way byte channel inside the kernel, created by pipe, with a read end and a write end, each a file descriptor. Bytes written to the write end are held in a kernel buffer and come out of the read end in the same order.

Example: a parent creates a pipe, forks, and the child writes a message that the parent reads; both processes use ordinary write and read.

Check yourself: 1. Which element of the array is the read end? 2. What does read return when all write ends are closed and the pipe is empty? 3. Why does the parent close fd[1]?