2

If I have an arbitrary number of pipe sources and sinks

exec1 | exec2 | exec3 | ...

QUESTION

  1. Then if execN exits, will all execM downstream (M > N) also exit?
  2. What will happen to the ones upstream (M < N)?
Bob
  • 4,220
  • 6
  • 29
  • 89

1 Answers1

6

Downstream processes won't necessarily exit. When execN exits, it closes the write end of the pipe, which closes the read end of execN+1's standard input. But until execN+1 tries to read from standard input, it won't notice, and even then, it's will simply detect that it has reached the end of the file; it can continue do other things or exit, as it decides.

Upstream, execN-1 won't notice that execN has exited and closed its read end of the pipe until execN-1 tries to write to its end of the pipe, at which point it will receive a SIGPIPE signal. The default handler for that signal is to exit, but execN-1 can install its own handler to decide what when and if that situation occurs.

chepner
  • 446,329
  • 63
  • 468
  • 610
  • 1
    See [this question](https://stackoverflow.com/questions/19120263/why-exit-code-141-with-grep-q) for an example of a process exiting and causing a SIGPIPE for the upstream process. – Gordon Davisson Feb 09 '20 at 22:38