Pipes
Overview
Pipes provide a way for processes to communicate. An example running wc
with standard input connected to the read end of pipe:
dup(p[0])
: The child dups the read end onto file descriptor 0. When wc reads from its standard input, it reads from the pipe.
Diagram
close(0) closes the fd 0. Make it available for next request. dup
makes fd 0 pointing pipe read side. fd
is just an index within process, points to a file opened by process. fd
could be changed to point to different file. Any program wants to read from fd 0 (standard input) now read from pipe read side.
Pipe Read, Write, Close
Read side of pipe
If no data is available, a read on a pipe waits for either data to be written or all file descriptors referring to the write end to be closed.
Pipe close
When all file descriptors for write side of pipe closed, the pipe write side is considered to be closed. It wakens up read side to perform one more read. If buffer contains nothing, piperead
returns 0 just like EOF.
How shell implements pipelines
echo hi | wc
left side writes to fd
1
. Right side reads from fd 0
.
Last updated