4

In the following chain of piped commands, when an interrupt is sent with Ctrl-C, ping is able to print its summary statistics before exiting, as long as tee has the -i (ignore interrupts) flag:

ping -D localhost 2>&1 | tee -a -i ping.log

However, with another command in the chain, ping's summary does not get printed:

ping -D localhost 2>&1 | sed -u 's/^\[\([0-9]*\.[0-9]*\)\]\(.*$\)/echo "[`date -d @\1 +"%Y-%m-%d %H:%M:%S"`] \2"/e' | tee -a -i ping.log

How can the above be made to print the summary?

Does sed have an option to ignore interrupts? In general how can interrupts be handled gracefully with piped commands?

4

ping -D localhost 2>&1 | (trap '' INT; exec sed -u 's/^\[\([0-9]*\.[0-9]*\)\]\(.*$\)/echo "[`date -d @\1 +"%Y-%m-%d %H:%M:%S"`] \2"/e') | tee -a -i ping.log

Calling trap '' INT tells the shell to ignore SIGINT. The exec is optional but nice to have, since the subshell process is no longer necessary after the trap.

2
  • Thanks that works. Is this approach of using a trap statement in a pipe considered good practice? Which signals can/should be intercepted in this way?
    – adatum
    Sep 12 '18 at 0:21
  • 2
    I can't think of anything wrong with using trap like this. You can't intercept SIGKILL or SIGSTOP this way (or any other way). You shouldn't intercept SIGFPE, SIGILL, or SIGSEGV, as this can cause undefined behavior. You can try to intercept SIGCHLD, but this may get reset depending on what flavor of Unix/Linux you're on. Anything else is fine, as long as the program you're executing doesn't care about it. Sep 12 '18 at 0:24

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.