Contents /
Previous /
Next
Trap Signals
The trap Command is used to make your script
perform certain actions in response to a signal.
List of Common Signals:
(See also the "man 7 signal" and /usr/include/asm/signal.h )
SIGHUP (1) Hang up.
SIGINT (2) Interrupt from keyboard. Issued if you press ^C.
SIGQUIT (3) Quit from keyboard. Issued if you press ^D.
SIGFPE (8) Floating point exception.
SIGKILL (9) Kill signal.
SIGTERM (15) Terminate. Cause the program to quit gracefully
SIGCHLD (17) Child terminate.
To trap a signal, create a function and then use
the trap command to bind the function to the signal:
#!/bin/sh
function on_hangup ()
{
echo 'Hangup (SIGHUP) signal received'
}
trap on_hangup SIGHUP
while true ; do
sleep 1
done
exit 0
Run the above script and then send the process ID
(use ps to find out) the -HUP signal to test it:
kill -HUP ID
If - is given instead of a function name,
then the signal is unbound
(i.e., set to its default value).
The script can trap the special signal EXIT
to clean up on exit:
#!/bin/sh
function on_exit ()
{
echo 'I should remove temp files now'
}
trap on_exit EXIT
while true ; do
sleep 1
done
exit 0