In yes | head
, yes
is terminated by a SIGPIPE signal the next time it writes a line after the other end of the pipe is closed (when head
exits).
In:
(seq 20; sleep 10; seq 10) | head
The subshell and children will be able to write the first 20 lines to the pipe (as that fits in the pipe buffer), and will then sleep 10 seconds unharmed. Meanwhile, head
will have died, but it's only when the subshell writes more lines to the pipe that it will be killed.
If you wanted your command to be killed as soon as head
returns, as opposed to the first time it writes something to the pipe after head
has returned, with bash
you could do:
{ head; kill "$!"; } < <(exec custom-program < large-file)
(bash
so happens to store the pid of process substitution in $!
).
See also Grep slow to exit after finding match? for a more portable approach, or limit find output AND avoid signal 13 for one applied to find
.
Or for the reverse this answer (run_under_watch
function) to a similar Q&A to kill a process as soon as its stdin becomes a broken pipe.
journald -f
exit after some log line is observed. It does exit but only after more log lines come and it tries to write again. – akostadinov Nov 13 '17 at 17:49