Explain how pipes work for communication between a parent and child process.
Last updated
A pipe is a unidirectional in-kernel byte stream with two file descriptors: one read end and one write end. A parent creates it before forking so the child inherits the same descriptors, giving both processes a shared communication channel.
Creation and inheritance:
pipe(fd) returns
fd[0](read) andfd[1](write).After
fork(), the child inherits copies of both descriptors, so they point at the same kernel pipe buffer.
Set the direction: Each side closes the end it doesn't use (e.g. parent closes read, child closes write) to fix a one-way flow and enable proper EOF detection.
Kernel-buffered byte stream:
Data written flows through a fixed-size kernel buffer; there are no message boundaries, just bytes.
A full buffer blocks the writer; an empty buffer blocks the reader (flow control for free).
EOF and errors:
When all write ends are closed, the reader gets EOF (read returns 0).
Writing when no read end is open raises
SIGPIPE.
Limitation: anonymous pipes only work between related processes; use a named pipe (
mkfifo) for unrelated processes.
[lang:c]
int fd[2];
pipe(fd);
if (fork() == 0) { // child
close(fd[1]); // close write end
read(fd[0], buf, n);
} else { // parent
close(fd[0]); // close read end
write(fd[1], msg, len);
}