Anatomy of a pipe
What you'll learn: Understand how a pipe acts as a one-way data bridge between two file descriptors in memory.
The Plumbing Analogy
In systems programming, a pipe is a unidirectional communication channel managed by the operating system kernel. Imagine a literal physical pipe: you pour water into one end (the write end), and it flows out the other (the read end).
Data in a pipe works on a "First-In, First-Out" (FIFO) basis. If you write the characters A, B, and C into the pipe, the process on the other side will receive them in that exact order. The pipe acts as a temporary buffer in the RAM; once data is read, it is removed from the buffer to make room for more.
The pipe() System Call
To create a pipe in C, you use the pipe() function. This function requires an array of two integers. These integers represent file descriptors—unique IDs the OS uses to track open files or streams.
fd[0]: The read end (think of the0as a mouth).fd[1]: The write end (think of the1as a pen).
#include <stdio.h>
#include <unistd.h>
int main() {
int fd[2];
// Create the pipe
if (pipe(fd) == -1) {
perror("Pipe failed");
return 1;
}
printf("Read end: fd[%d]\n", fd[0]);
printf("Write end: fd[%d]\n", fd[1]);
// Data flows from fd[1] -> fd[0]
return 0;
}
How the Kernel Handles It
When you call pipe(), the kernel sets up a small piece of shared memory. It then gives your process two specific keys (the file descriptors) to access that memory.
Crucially, a pipe is blocking. If a process tries to read from an empty pipe, it will "pause" (sleep) until data is written to the other end. Similarly, if the pipe’s memory buffer gets full, a writing process will pause until the reader clears some space. This automatic synchronization is what makes pipes so powerful for coordinating different parts of a system.
Key takeaway
A pipe is a one-way kernel buffer accessed via two file descriptors: fd[0] for reading and fd[1] for writing.