syscalls

pipe2() — Linux system interface

Create a pipe with flags set atomically at creation. O_CLOEXEC marks both descriptors close-on-exec; O_NONBLOCK sets nonblocking status on both ends. An empty nonblocking pipe with a writer still open returns EAGAIN rather than EOF. Unsupported flags cause EINVAL. Avoid creating descriptors then setting CLOEXEC separately in a concurrent exec-capable application. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. Linux-specific interface or flags; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#define _GNU_SOURCE#include <fcntl.h>#include <unistd.h>int pipe2(int pipefd[2], int flags);

Parameters & Attributes

NameTypeDescription
pipefdint[2]Output array for read and write ends.
flagsintZero or supported pipe2 flags.

Return Value

int

0 on success. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \    fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \    return EXIT_FAILURE; \} } while (0)
int main(void){    int f[2]; char b;    CHECK(pipe2(f, O_CLOEXEC | O_NONBLOCK) == 0);    for (int i = 0; i < 2; ++i) {        int d = fcntl(f[i], F_GETFD), s = fcntl(f[i], F_GETFL);        CHECK(d >= 0 && (d & FD_CLOEXEC));        CHECK(s >= 0 && (s & O_NONBLOCK));    }    CHECK(read(f[0], &b, 1) == -1 && errno == EAGAIN);    CHECK(close(f[1]) == 0);    CHECK(read(f[0], &b, 1) == 0);    CHECK(close(f[0]) == 0);    puts("both flags set; EAGAIN then EOF");    return EXIT_SUCCESS;}
Linux Reference