Pipes & FIFOs
Connect processes with pipes and named FIFOs like a shell pipeline does.
By Invicly Tech, , in Linux System Programming. About 11 minutes to read.
In short
A pipe is a one-way kernel buffer with a read end and a write end, created with pipe and usually shared with a child through fork. A FIFO is the same thing with a name in the file system, so unrelated processes can open it. Shell pipelines like ls | wc -l are built from pipe, fork, dup2 and exec.
Explained simply
A pipe is a one-way tube inside the kernel. One process pushes bytes in at one end, another pulls them out at the other end, in the same order. Nothing is stored on disk. When you type ls | wc -l, the shell builds exactly such a tube between ls and wc.
A pipe has two file descriptors: one for reading and one for writing. Usually a process creates the pipe, then forks, so the child gets copies of both ends. Each side then closes the end it does not need, and the two processes can talk.
The tube has a limited size. If the writer is faster than the reader and the tube fills up, the writer simply waits. If the tube is empty, the reader waits. This automatic waiting keeps a fast program from flooding a slow one.
A FIFO, also called a named pipe, is the same tube with a name in the file system, like /tmp/mypipe. Any two programs that know the name can open it, even if they are not parent and child.
Press Play on a diagram to walk through it one step at a time.
- 1pipe(fds)
fds[0] is the read end, fds[1] the write end.
- 2Fork child 1
dup2(fds[1], 1), close both ends, exec ls.
- 3Fork child 2
dup2(fds[0], 0), close both ends, exec wc -l.
- 4Parent closes both ends
Otherwise wc never sees EOF.
- 5Wait for both
Collect both exit statuses.
- Reader calls read
- Data waiting: returns up to that much
- Empty, writers open: blocks (or EAGAIN)
- Empty, no writers: returns 0 (EOF)
- Writer calls write
- Space free: copies data in
- Full: blocks (or EAGAIN)
- No readers: SIGPIPE or EPIPE
In depth
Pipe capacity, blocking and atomic writes
On Linux a pipe holds 65536 bytes (16 pages) by default. You can read the size with fcntl(fd, F_GETPIPE_SZ) and change it with F_SETPIPE_SZ, up to the limit in /proc/sys/fs/pipe-max-size (1 MiB by default for normal users). When the buffer is full, write blocks; when it is empty, read blocks. With O_NONBLOCK both return -1 with EAGAIN instead.
Writes of PIPE_BUF bytes or fewer (4096 on Linux) are atomic: if several processes write to the same pipe, each small write arrives in one piece. Larger writes can be split and mixed with other writers' data. This is why many processes can safely log short lines into one pipe, but not large blocks.
- read may return fewer bytes than you asked for; always loop
- pipe2(fds, O_CLOEXEC | O_NONBLOCK) sets flags in one step
- ulimit -p shows PIPE_BUF in 512-byte units on some shells
EOF, SIGPIPE and why you must close unused ends
The kernel counts how many descriptors point at each end. A reader gets EOF (read returns 0) only when the buffer is empty and every write end is closed, in every process. A writer whose pipe has no read end left gets SIGPIPE, which ends the process by default; if SIGPIPE is ignored, write fails with EPIPE instead.
This is why every unused end must be closed. After fork, the parent and the child both hold both ends. If the parent keeps its copy of the write end open, the reader never sees EOF and waits forever. The command yes | head -1 shows SIGPIPE at work: head exits after one line, and yes is killed by SIGPIPE the next time it writes, so its exit status is 141 (128 + 13).
- Hang with no output: look for a stray write end
- echo "${PIPESTATUS[@]}" in bash shows every stage's exit code
- Servers usually ignore SIGPIPE and check writes for EPIPE
Wiring a longer pipeline
A pipeline of N commands needs N minus 1 pipes. Each child connects its input to the read end of the pipe on its left and its output to the write end of the pipe on its right, using dup2, then closes every original pipe descriptor before exec. The first command keeps the terminal as its input and the last keeps it as its output.
The parent creates pipes one at a time as it goes: after forking command i, it closes the read end of the previous pipe and the write end of the current pipe, and remembers the current read end for the next command. This way no process ever holds more pipe ends than it needs. Finally the parent waits for all children; shells report the exit code of the last command unless set -o pipefail is on.
- fd 0: the terminal
- fd 1: pipe A write end
- All other pipe fds closed
- fd 0: pipe A read end
- fd 1: pipe B write end
- All other pipe fds closed
- fd 0: pipe B read end
- fd 1: the terminal
- All other pipe fds closed
FIFOs: opening rules and server patterns
mkfifo(path, 0600) or the mkfifo command creates a FIFO. The data still goes through a kernel buffer; the file is only a meeting point. Opening has special rules: open for reading blocks until someone opens for writing, and the reverse. With O_NONBLOCK, opening for reading succeeds at once, while opening write-only fails with ENXIO if no reader exists yet.
A common pattern is a server that reads requests from one well-known FIFO. When the last client closes its write end, the server reads EOF, which is usually not what you want. The usual fix is for the server to also open the FIFO for writing itself and keep that descriptor open, so the writer count never drops to zero. Keep each client message at or below PIPE_BUF bytes, so messages from different clients never mix.
- Reader to Kernel: open("/tmp/jobs", O_RDONLY) blocks1open("/tmp/jobs", O_RDONLY) blocks
- Writer to Kernel: open("/tmp/jobs", O_WRONLY)2open("/tmp/jobs", O_WRONLY)
- Kernel to Reader: both opens return3both opens return
- Writer to Reader: write("job 1\n") arrives in order4write("job 1\n") arrives in order
- Writer to Kernel: close: last writer gone5close: last writer gone
- Kernel to Reader: read returns 0 (EOF)6read returns 0 (EOF)
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Create a pipe and fork~50m
- 2Close unused pipe ends~50m
- 3Build a two-command pipeline with dup2~50m
- 4Create a named FIFO with mkfifo~50m
- 5Explain SIGPIPE and EOF behaviour~50m
Key points
- Close every unused end; a reader sees EOF only when all write ends are closed.
- Writing to a pipe with no readers raises SIGPIPE or fails with EPIPE.
- Writes of up to PIPE_BUF bytes (4096 on Linux) are atomic.
- A full pipe blocks the writer, giving natural back-pressure.
Key terms
Tap a card to flip it. 0/5 known
Examples
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int fds[2]; pipe(fds);
if (fork() == 0) { // child: writer
close(fds[0]);
write(fds[1], "ping\n", 5);
_exit(0);
}
close(fds[1]); // parent: reader
char buf[16]; ssize_t n = read(fds[0], buf, sizeof buf);
printf("parent read %zd bytes\n", n); wait(NULL);
return 0;
}Parent and child talk through a pipe; each closes the end it does not use.
Capture a command's output, like popen
You want the output of date inside your program. Step 1: create a pipe. Step 2: fork; the child moves the write end onto stdout with dup2, closes both original ends and execs date. Step 3: the parent closes the write end (otherwise it never sees EOF) and reads until read returns 0. Step 4: wait for the child to collect its status.
int fds[2];
if (pipe(fds) < 0) { perror("pipe"); return 1; }
pid_t pid = fork();
if (pid < 0) { perror("fork"); return 1; }
if (pid == 0) {
dup2(fds[1], STDOUT_FILENO); close(fds[0]); close(fds[1]);
execlp("date", "date", "+%F %T", (char *)NULL); perror("execlp"); _exit(127);
}
close(fds[1]); /* essential, or no EOF */
char buf[256]; ssize_t n; size_t total = 0;
while ((n = read(fds[0], buf + total, sizeof buf - 1 - total)) > 0) total += (size_t)n;
buf[total] = '\0'; close(fds[0]);
waitpid(pid, NULL, 0);
printf("date said: %s", buf);A FIFO between two terminals
Two unrelated shells can talk through a FIFO. Step 1: create it. Step 2: in terminal 1, start a reader; it blocks until a writer appears. Step 3: in terminal 2, send lines. Step 4: when the writer closes, the reader sees EOF and cat exits. The reader loop in the last line reopens the FIFO each time, a simple way to keep a log collector alive between writers.
mkfifo -m 600 /tmp/logpipe
ls -l /tmp/logpipe # type p: prw-------
# terminal 1
cat /tmp/logpipe # blocks until a writer opens
# terminal 2
echo "build finished" > /tmp/logpipe
# a collector that survives many writers
while true; do cat /tmp/logpipe >> collected.log; doneQuick reference
- pipe(fds): fds[0] is the read end, fds[1] the write end
- Default pipe capacity on Linux is 64 KiB; change it with F_SETPIPE_SZ
- Writes up to PIPE_BUF (4096 bytes) are atomic between writers
- EOF arrives only when every write end in every process is closed
- Exit status 141 means the process was killed by SIGPIPE
- mkfifo name creates a named pipe; ls -l shows it with type p
- Opening a FIFO blocks until the other side opens too
- set -o pipefail makes a pipeline fail if any stage fails
Common mistakes
- Leaving a write end open in the parent so the reader hangs forever.
- Ignoring SIGPIPE in a server and then not checking writes for EPIPE.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Show the exit status of each stage of yes | head -3 and explain the numbers.
- Exercise 2medium
Write a C program that runs ls | wc -l using pipe, two forks, dup2 and execlp, and waits for both children.
- Exercise 3hard
Write a FIFO server that reads newline-terminated requests from /tmp/reqs forever, without exiting when clients disconnect, and prints each line.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a pipe and a FIFO?
- They work the same way, but a pipe has no name and is shared only through fork, while a FIFO has a path in the file system so unrelated processes can open it.
- Is data in a named pipe written to disk?
- No. The FIFO file is only a name; the data passes through a kernel buffer in memory.
- Can a pipe be used in both directions?
- No, a pipe is one-way. Use two pipes, or a Unix socket pair made with socketpair, for two-way talk.
- Why does my pipeline hang?
- Usually some process still holds a write end, so the reader never gets EOF. Close every unused end after fork.