Bash – Proper way to shut down consumer

bashpipeshell

Say we have a simple pipeline:

set -eo pipefail;
echo 'foo' | cat

how does cat know when to exit? Is it when the STDIN stream ends, or does cat receive a signal? In my case, the producer process receives a SIGINT and then exits with code 1, so how can cat (consumer process) know which exit code the producer process exited with?

Best Answer

cat doesn't know about echo's signals. It receives end-of-file condition per man pipe(7):

If all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from the pipe will see end- of-file (read(2) will return 0).

For writers to the pipe, however, there is SIGPIPE. See the same man page

Related Question