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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. 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 read do 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. EAGAIN only appears in non-blocking mode, and SIGPIPE hits 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, read blocks 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 and p[1] writes. Both are open in the calling process: fork is what then lets a child share them.

  • A program runs ls | wc -l with pipe, fork, dup2 and exec. ls finishes but wc stays 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

    wc reads until end of file, which only comes when every write descriptor is closed. The parent holds one: it must close(p[1]) after the fork. If ls has finished, the pipe cannot be full.