Skip to content
systemcoding.dev
Systems Programming

Create a pipe and read and write both ends

pipe fills a two-element array with a read end and a write end, and one process can write and read both ends because the kernel buffers the data.

1 min read
Summarize in AI

pipe(fd) returns two descriptors: fd[0] reads and fd[1] writes. Whatever goes into the write end waits in a kernel buffer until it is read from the other, which means a single process can round-trip a message without any child at all. That makes it the smallest way to see how a pipe behaves before you add fork.

pipe1.cc
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
    int fd[2];
    char buf[16];

    if (pipe(fd) == -1) {
        perror("pipe");
        return 1;
    }
    write(fd[1], "hello", 5);

    ssize_t n = read(fd[0], buf, sizeof buf);
    printf("read %zd bytes: %.*s\n", n, (int)n, buf);

    close(fd[0]);
    close(fd[1]);
    return 0;
}
Text
read 5 bytes: hello

The read returns what is there, 5 bytes, not the 16 you asked for, because a pipe is a byte stream and read never waits to fill the buffer once any data is available. Had you called read first, it would block forever, since this process holds the only write end and never writes. Use pipe2(fd, O_CLOEXEC) on Linux with glibc 2.9 or later when the descriptors must not leak across exec; see pipe(2).

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.