Say we have a simple pipeline:

a | b

say, a exits - is there a surefire way to keep b alive for an arbitrary amount of time (to complete a task etc).

  • 1
    "If the pipeline is not executed asynchronously (see Lists), the shell waits for all commands in the pipeline to complete." – Jesse_b Jul 24 at 21:29

b would not be terminated by a terminating.

$ { echo hello; } | { read message; printf 'got "%s"\n' "$message"; sleep 5; echo "ok, I'm done"; }
got "hello"
ok, I'm done

Here, a (the echo hello) would simply output a string and terminate. The right hand side of the pipe (b) would read the string, output it, sleep for a while, and then do its final echo before terminating.

If b was terminated when a was, it would never have time to do what it needed to do. The only thing b can't do here is to read more data from its standard input (an extra read at the end would get end-of-file immediately).

In the other scenario (not mentioned in the question), where b terminates before a, a would receive a PIPE signal if it tried to write to its standard output (across to the non-existing b process) and terminate from that (by default).

If it didn't try to write to the pipe, a would continue running until done.

  • ah nice, I always wondered when SIGPIPE was raised, so SIGPIPE is received by a if b exits before a? – Alexander Mills Jul 24 at 21:42
  • 1
    @AlexanderMills Yes, correct, but only if a tries to write to standard output. – Kusalananda Jul 24 at 21:42
  • or stderr I assume (if stderr is connect to the consumer) – Alexander Mills Jul 24 at 21:43
  • 1
    @AlexanderMills Ok, only if a tries to write to the pipe, no matter what the stream is that is connected to it. – Kusalananda Jul 24 at 21:43

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.