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

Unidirectional flow in pipes

Unidirectional flow in pipes

What you'll learn: You'll understand how a pipe acts as a one-way street for data between a parent and child process.

The One-Way Street

In systems programming, a pipe is the simplest way for two processes to talk to each other. The most important rule to remember is that pipes are unidirectional. Think of a pipe like a physical water slide: you can jump in at the top (the write end) and slide down to the bottom (the read end), but you can never climb back up.

When you create a pipe, the operating system gives you two file descriptors:

  1. A "read" end (where data comes out).
  2. A "write" end (where data goes in).

If you want two processes to talk back and forth (bidirectional communication), you actually need to create two separate pipes—one for each direction.

Handing off the Pipe

When we use the fork() command, the child process inherits the pipe from the parent. To keep things clean and prevent data collisions, it is standard practice for each process to immediately close the end it isn't using. If the parent is the "sender," it closes the read end. If the child is the "receiver," it closes the write end.

Here is how that looks in code:

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

int main() {
    int fd[2]; // fd[0] is read, fd[1] is write
    pipe(fd);

    if (fork() == 0) {
        // CHILD: We only want to receive data
        close(fd[1]); // Close the unused write end

        char buffer[20];
        read(fd[0], buffer, 20);
        printf("Child received: %s\n", buffer);

        close(fd[0]);
    } else {
        // PARENT: We only want to send data
        close(fd[0]); // Close the unused read end

        char *msg = "Hello, child!";
        write(fd[1], msg, 14);

        close(fd[1]);
    }
    return 0;
}

Why Unidirectional?

You might wonder why we can't just use one pipe for both ways. Imagine two people trying to talk through a very thin tube at the exact same time. Their voices would clash, and neither would hear the other clearly. By forcing the data to flow in only one direction, the operating system ensures that data stays in the correct order and reaches the destination without getting "tangled" with outgoing messages.

Key takeaway

A pipe is a strictly one-way communication channel where data flows from a write-end to a read-end.