4

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?

13

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

  • Is there a way to trap (or listen for) the end-of-file condition in the consumer? – Alexander Mills Sep 22 at 1:05
  • Also, is there any way for the consumer to know the exit code of the producer process? – Alexander Mills Sep 22 at 1:09
  • 1
    @AlexanderMills For the first, absolutely; if you're writing in C, you can call feof(STDIN) or whatever. For the second, no; only the process's parent knows its exit code. – Draconis Sep 22 at 1:11
  • @AlexanderMills Draconis already addressed end-of-file part, but as far as exit code goes the best answer here is probably "not with simple shell pipe". If it's a pipeline created via C or Python code, in theory you could have both producer and consumer share a resource and write exit code to it. But of course that means both producer and consumer code are under your direct control. Maybe something like this would work (echo "I'm a producer"; echo $? ) | some_consumer.py but that implies consumer has to always check last line for a numeric string and handle cases when it's not. – Sergiy Kolodyazhnyy Sep 22 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.