Course contentsShow
← C
Lesson 1101 of 1,21915. Systems ProgrammingFree lesson

Creating pipes with pipe()

Creating pipes with pipe()

What you'll learn: How to establish a unidirectional data channel between two processes using the pipe() system call.

The Plumbing of Processes

Imagine you are building a house. To move water from the utility main to your kitchen, you need a pipe. In C, if you want to move data from one process to another, you need a literal pipe.

A pipe is a unidirectional data channel. It has two ends: a "read end" where you soak up data, and a "write end" where you pour data in. It follows a First-In, First-Out (FIFO) rule—the first byte you shove into the pipe is the first byte the other process pulls out.

The pipe() System Call

To create this channel, we use the pipe() function. It takes an array of two integers as an argument. These integers represent file descriptors, which are essentially ID numbers the operating system uses to track open files or streams.

  • fd[0] is the read end (think of the '0' as an 'o' for "output from the pipe").
  • fd[1] is the write end (think of the '1' as an 'i' for "input into the pipe").

If pipe() succeeds, it returns 0. If it fails (perhaps the system has too many open files), it returns -1.

A Basic Implementation

Here is how you initialize a pipe in your code:

#include <stdio.h>
#include <unistd.h>

int main() {
    int pipefds[2];
    int status;

    // Create the pipe
    status = pipe(pipefds);

    if (status == -1) {
        perror("Pipe creation failed");
        return 1;
    }

    printf("Pipe created successfully!\n");
    printf("Read end (fd[0]): %d\n", pipefds[0]);
    printf("Write end (fd[1]): %d\n", pipefds[1]);

    // Usually, you would fork() here to share these with a child...
    
    return 0;
}

How It Works

When you call pipe(), the kernel sets up a buffer in memory. You don't see this buffer; you just interact with it using the file descriptors.

The real magic happens when you pair pipe() with fork(). Because a child process inherits a copy of the parent’s file descriptors, both processes will point to the same pipe. This allows one process to write data into fd[1] while the other process reads that exact same data from fd[0].

Key takeaway

The pipe() function creates a pair of file descriptors—fd[0] for reading and fd[1] for writing—enabling a one-way flow of data between related processes.