Why is this pipe terminated?

2019-02-21 08:25发布

问题:

This is a piped command for generating 10 characters password at random:

cat /dev/urandom | base64 | head -c 10

My question is cat /dev/urandom | base64 is an infinite output stream which will not stop by itself. But why appending head -c 10 makes the whole pipe terminated? I assume cat, base64 and head are 3 separated processes, how can head terminate the cat?

回答1:

After base64 outputs 10 bytes, head gets enough inputs and exits. When the former attempts to output more bytes, it will receive SIGPIPE signal and hence exit too。For the same reason, cat will exit in turn.



回答2:

head closes the input file after reading the required amount. when a pipe is closed from one side, the other side gets write errors; this causes base64 to close, which in turn causes cat to close.



回答3:

Piping works by connection the output of one process A to the input of B. The connection can be broken, when

  • A closes its output. B will get EOF.
  • B closes its input. A will get an error that the output is no longer available when it tries to write the next byte.

Since these two cases are so common, the handling has been moved into the C standard lib.