Pipes
The pipe created by pipe and its two descriptors, how fork inherits it, end of file and SIGPIPE, capacity and blocking, dup2 to plug standard input or output, and the named pipe created by mkfifo.
- 29 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Pipe: what is it?
Show the answer
A one-way channel managed by the kernel: what one process writes at one end, another reads at the other end, in the same order.
It is a stream of bytes with no boundaries between messages. It lives in the kernel and disappears when every descriptor referring to it is closed. In
ls | wc -l, the shell creates one between the two commands.A pipe is empty and a process still holds its write end open. What does
readdo on the read end?- It blocks until data arrives or until every writer has closed
- It returns 0 at once, as at the end of a file
- It returns -1 with the EAGAIN error and the process carries on
- It sends SIGPIPE to the reader, which is then terminated
Show the answer
It blocks until data arrives or until every writer has closed
Returning 0 is reserved for when no writer exists any more.
EAGAINonly appears in non-blocking mode, andSIGPIPEhits the writer, never the reader.On a pipe, read returns 0, which is …, when the pipe is empty and every … descriptor is closed.
Show the answer
On a pipe, read returns 0, which is end of file, when the pipe is empty and every write descriptor is closed.
As long as a single write descriptor remains open, even in another process,
readblocks instead of returning 0: a reader cannot know whether the writer will write again.pipe(int p[2]): what is it?
Show the answer
The system call that creates a kernel channel and stores two descriptors in the array: the first for reading, the second for writing.
After
pipe(p),p[0]reads andp[1]writes. Both are open in the calling process:forkis what then lets a child share them.A program runs
ls | wc -lwith pipe, fork, dup2 and exec.lsfinishes butwcstays blocked forever. What is the probable cause?- The pipe is full and ls stayed blocked writing
- wc received SIGPIPE and is now waiting for one more signal
- The parent kept p[1] open: wc never sees end of file
- dup2 closed p[0] in the parent, so wc can no longer read
Show the answer
The parent kept p[1] open: wc never sees end of file
wcreads until end of file, which only comes when every write descriptor is closed. The parent holds one: it mustclose(p[1])after thefork. Iflshas finished, the pipe cannot be full.