What's Signal
When a signal is received, a script can do one of three actions:
- Ignore it and do nothing.
- Catch the signal using trap and take appropriate action.
- Take the default action.
All the above is true except for the following signals:
SIGKILL (signal 9)
SIGSTOP (signal 17)
SIGCONT (signal 19)
These cannot be caught and always uses the default action.
Signal Syntax
trap [ command ] signal [ signal ... ]
- Command can be explicit commands or a function
- Command
trap 'echo signal received, now exiting..; exit' 2 6
- Command
- function
function mysignal { echo "in mysignal function" exit } trap 'mysignal' 2 6
- function
- Signal can be a signal number or signal name
Signals numbers from 0 to 31, "0" being a pseudo-signal meaning "program termination", or using name, HUP for HANGUP signal, TERM for the SIGTERM signal etc.
trap 'echo signal received, now exiting..; exit' 2 6 trap 'echo signal received, now exiting..; exit' SIGINT SIGQUIT
What will script do when a signal(for example 15) is received:
- The script would trap the signal 15, and execute the command "rm -f $Tmp", thus removing the temporary file.
- it would continue with the next script command. This could cause strange results, because the (probably needed) temporary file $Tmp is gone. Another point is that somebody explicitly tried to terminate the script, a fact it deliberately ignores.
How to ignore and reset default signal handler
To ignore a signal, use two single quotes in place of the command:
trap '' signals
To reset a trap use:
trap - signals
KSH Signal Code Samples
1 #!/bin/ksh 2 3 function mysignal { 4 echo "in mysignal" 5 #exit 6 } 7 8 trap "mysignal" SIGINT SIGQUIT 9 10 function mainfun { 11 sleep 10 12 } 13 14 mainfun 15 16 echo "End of script"
When script is running, and CTRL-2 is pressed, function mysignal will be called, and after function is finished, control-flow come to the statement immediately after 'mainfun', so the final "End of script" is executed.
So if line 5 (#exit) is not commented out, line 16 will not be executed, because script will exit at line 5.