Well-behaved programs save data and shut down cleanly when they receive a SIGTERM signal. The trap command assigns a signal handler to signals in a script. Once a function is assigned to a signal using the trap command, when a script receives a signal, this function is executed.
The syntax is as follows:
trap 'signal_handler_function_name' SIGNAL LIST
SIGNAL LIST is space-delimited. It can include both signal numbers and signal names.
This shell script responds to the SIGINT signal:
#/bin/bash
#Filename: sighandle.sh
#Description: Signal handler
function handler()
{
echo Hey, received signal : SIGINT
}
# $$ is a special variable that returns process ID of current
# process/script
echo My process ID is $$
#handler is the name of the signal handler function for SIGINT signal
trap 'handler' SIGINT
while true;
do
sleep 1
done
Run this script in a terminal. When the script is running, pressing Ctrl + C it will show the message by executing the signal handler associated with it. Ctrl + C corresponds to a SIGINT signal.
The while loop is used to keep the process running forever without being terminated. This is done so the script can respond to signals. The loop to keep a process alive infinitely is often called the event loop.
If the process ID of the script is given, the kill command can send a signal to it:
$ kill -s SIGINT PROCESS_ID
The process ID of the preceding script will be printed when it is executed; alternatively, you can find it with the ps command.
If no signal handlers are specified for signals, a script will call the default signal handlers assigned by the operating system. Generally, pressing Ctrl + C will terminate a program, as the default handler provided by the operating system will terminate the process. The custom handler defined here overrides the default handler.
We can define signal handlers for any signals available (kill -l) with the trap command. A single signal handler can process multiple signals.