C Reference ยท POSIX and Systems
C pipe() function
Reference for pipe(): create a one-way byte channel, connect parent and child processes, use dup2 to redirect output, and avoid the classic deadlocks.
pipe() creates a one-way channel in the kernel: bytes written to one end can be read from the other, in order. It returns two file descriptors, fd[0] for reading and fd[1] for writing. By itself a pipe connects a process to itself; its real purpose appears after fork, when parent and child inherit both ends and use them to talk.
This is how shells implement a | b. Each process closes the end it does not use, and dup2 can attach a pipe end to standard input or output so an unmodified program takes part without knowing it.
#include <unistd.h> int fd[2]; pipe(fd); /* fd[0]: read end, fd[1]: write end */
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#include <unistd.h> int pipe(int fd[2]); int pipe2(int fd[2], int flags); /* Linux, BSDs, POSIX.1-2024: O_CLOEXEC, O_NONBLOCK */
| Name | Description |
|---|---|
fd |
An array of two ints. On success fd[0] is the read end and fd[1] is the write end. |
flags |
(pipe2) O_CLOEXEC and/or O_NONBLOCK. |
Returns: 0 on success, -1 on failure.
Errors: EMFILE (the process has too many descriptors open), ENFILE (system-wide limit), EFAULT (bad pointer).
Usage notes
- End of file:
readreturns0only when every write end is closed. If the parent forgets to close its own copy offd[1], the read loop waits forever. Close unused ends in every process. - Writing with no reader: when all read ends are closed,
writeraisesSIGPIPE(which kills the process by default) or fails withEPIPEif the signal is ignored. - Blocking:
readblocks while the pipe is empty and writers exist;writeblocks while the pipe is full. The capacity is typically 64 KiB on Linux. Two processes that each wait for the other to read first will deadlock. - Writes of at most
PIPE_BUFbytes (at least 512, typically 4096) are atomic: they are never interleaved with other writers. - A pipe carries bytes, not messages. A single
writemay be received by severalreadcalls, or several writes by one. Frame your data (length prefix or delimiter). - A pipe is one-directional. For two-way communication create two pipes, or use a socket pair.
- Use
dup2(old, new)to makenewrefer to the same open file asold; close the original afterwards. popen()fromstdio.hwraps this pattern (fork, pipe,sh -c) for the simple cases.