Skip to content
AgileLogics
4 min read

Inter-Process Communication: Pipes

Prerequisites: Process management: fork and exec

A pipe connects one process's output to another's input — exactly what the shell's | operator sets up between two commands.

#include <unistd.h>

int main(void) {
    int fds[2];
    pipe(fds); // fds[0] = read end, fds[1] = write end

    if (fork() == 0) {
        close(fds[0]);
        write(fds[1], "Hello from child", 17);
        close(fds[1]);
    } else {
        close(fds[1]);
        char buffer[100];
        read(fds[0], buffer, sizeof(buffer));
        printf("Parent received: %s\n", buffer);
        close(fds[0]);
    }
    return 0;
}

Each process closes the end of the pipe it isn't using — a pipe left open unnecessarily can cause a reader to block forever waiting for a writer that will never close its end.