Inter-Process Communication

the anonymous pipe

Think of a length of garden hose: you pour water in one end and it comes out the other, in order, one direction only. An anonymous pipe is exactly that for bytes. One process writes bytes into one end, another process reads those same bytes out of the other end, first-in-first-out, and the data flows one way. It is the oldest and simplest way for two related processes to pass a stream of data.

Concretely, a process calls pipe(), and the kernel hands back two file descriptors: fd[0] is the read end, fd[1] is the write end. They behave like any file descriptor — you read() from fd[0] and write() to fd[1] — but there is no file on disk; the buffer lives in the kernel. The trick that makes it useful for IPC is fork(): the parent creates the pipe, then forks, and now the child inherits copies of both descriptors. Typically the parent closes the end it will not use and the child closes the other, leaving a clean one-way channel between them. This is why it is called 'anonymous' — it has no name in the filesystem, so only processes that inherited the descriptors (a parent and its descendants) can find it. Unrelated processes cannot.

Pipes carry a raw byte stream with no message boundaries: if the writer does two write() calls of 10 bytes each, the reader might receive all 20 in a single read(), or 5 then 15 — the pipe does not preserve how the bytes were grouped. The kernel buffer has a fixed capacity (commonly 64 KiB on Linux); when it fills, write() blocks until the reader drains some, which is natural backpressure. And there is a sharp hazard: if every read end is closed and a process still writes, it gets a SIGPIPE signal (default action: terminate the writer).

int fd[2]; pipe(fd); if (fork() == 0) { close(fd[1]); /* child reads */ read(fd[0], buf, n); } else { close(fd[0]); /* parent writes */ write(fd[1], "hi", 2); }

Create the pipe before forking; each side closes the end it does not use. That leftover pair is the channel.

An anonymous pipe is one-way. For two-way talk you need two pipes (or a socketpair). And because it has no filesystem name, it only connects a process to its own relatives — never two unrelated programs.

Also called
pipeunnamed pipe管線無名管線