Jay Taylor's notes

back to listing index

SignalTrap - Greg's Wiki

[web search]
Original source (mywiki.wooledge.org)
Tags: bash linux shell-scripting unix signals mywiki.wooledge.org
Clipped on: 2018-03-30

Image (Asset 1/1) alt=should kill itself with SIGINT rather than simply exiting, to avoid causing problems for its caller. Thus:

trap 'rm -f "$tempfile"; trap - INT; kill -INT $$' INT

We can see the difference between a properly behaving process and a misbehaving process. On most operating systems, ping is an example of a misbehaving process. It traps SIGINT in order to display a summary at the end, before exiting. But it fails to kill itself with SIGINT, and so the calling shell does not know that it should abort as well. For example,

# Bash.  Linux ping syntax.
for i in {1..254}; do
  ping -c 2 192.168.1.$i

Here, if the user presses Ctrl-C during the loop, it will terminate the current ping command, but it will not terminate the loop. This is because Linux's ping command does not kill itself with SIGINT in order to communicate to the caller that the SIGINT was fatal. (Linux is not unique in this respect; I do not know of any operating system whose ping command exhibits the correct behavior.)

A properly behaving process such as sleep does not have this problem:

while [ $i -le 100 ]; do
  printf "%d " $i
  sleep 1

If we press Ctrl-C during this loop, sleep will receive the SIGINT and die from it (sleep does not catch SIGINT). The shell sees that the sleep died from SIGINT. In the case of an interactive shell, this terminates the loop. In the case of a script, the whole script will exit, unless the script itself traps SIGINT.


SignalTrap (last edited 2017-05-28 22:24:18 by 104)