pipe()
int pipe(int pfd[2]);
- Purpose: Creates an anonymous pipe for Inter-Process Communication (IPC).
- Usage: Typically used between a parent and child process after
fork().
- Parameters:
pfd[2]: An integer array storing two file descriptors:
pfd[0] → Read end (used for reading from the pipe)
pfd[1] → Write end (used for writing to the pipe)
- Return Value:
0 on success (for pipe only).
-1 on failure (sets errno).
- Common Errors:
EMFILE: Too many file descriptors open.
ENFILE: System-wide file descriptor limit reached.
EFAULT: pfd points to an invalid memory address.
Pipe Communication Flow & Behavior
- Parent writes to pipe (
write(pfd[1], ...)).
- Child reads from pipe (
read(pfd[0], ...)).
- Data is transferred in a unidirectional manner (one writes, the other reads).
read() blocks if no data is available.
write() blocks if the pipe buffer is full.
- If all write ends are closed →
read() returns 0 (EOF).
- If all read ends are closed →
write() triggers SIGPIPE, terminating the process.
- Processes exit using
exit(0) after completing communication.
Pipe Buffer & Non-Blocking Mode
- Pipes have a fixed-size buffer (OS-dependent, typically 4KB - 64KB).
- When the pipe buffer is full,
write() blocks unless in non-blocking mode.
- When the pipe buffer is empty,
read() blocks unless in non-blocking mode.