Search code examples
unixpipeunix-head

Why doesn't "yes | head" hang?


Why doesn't yes | head hang?

I thought the system collects all of the result from yes and then pipes it to head, and because yes is an infinite loop, the system hangs. But, it can actually stop and show 10 lines of y.

How does the system manage to stop yes when head is done collecting data?


Solution

  • When you say yes | head the shell will arrange things such that the output of yes goes to a pipe and the input of head comes from that same pipe. When head reads 10 lines, it closes its STDIN_FILENO, thereby closing its end of the pipe. When yes tries to write to a closed pipe it gets a SIGPIPE whose default action is to kill it.

    A simple way to test this is with strace:

    $ strace yes | head
    y
    [...]
    y
    write(1, "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"..., 4096) = -1 EPIPE (Broken pipe)
    --- SIGPIPE {si_signo=SIGPIPE, si_code=SI_USER, si_pid=4069, si_uid=1000} ---
    +++ killed by SIGPIPE +++