Unix Pipes & IPC - Key Functions & Syntax
1. 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.
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.
2. read()
ssize_t read(int fd, void *buf, size_t count);
- Purpose: Reads data from a file descriptor (
fd
), typically from pfd[0]
(pipe read end).
- Usage: The process calls
read()
to retrieve data from the pipe.
- Parameters:
fd
: File descriptor (must be pfd[0]
for reading from a pipe).
buf
: Pointer to a buffer where the read data will be stored.
count
: The maximum number of bytes to read.
- Return Value:
>0
→ Number of bytes read successfully.
0
→ End of file (EOF) or all write ends of the pipe are closed.
1
→ Error occurred (errno
set).
- Blocking Behavior:
- If there’s no data in the pipe,
read()
blocks (waits) until data is available.
- If all write ends are closed,
read()
returns 0
(indicating EOF).
- Non-Blocking Mode:
- Set file descriptor as non-blocking using
fcntl(fd, F_SETFL, O_NONBLOCK)
.
- In non-blocking mode,
read()
returns 1
with errno = EAGAIN
if no data is available.
3. write()