You have probably pressed Ctrl + C or Ctrl + Z without knowing what was occurring—it’s just like pressing Ctrl + Alt + Delete in another OS, right? Well, in one regard, yes—it is a signal, but the action itself is very different in Linux. A signal at the hardware level is similar to a flag or some sort of immediate notification that says hey – something happened here. If the appropriate listener is set up, that signal can execute some sort of functionality.
On the other hand, software signaling is far more flexible and we can use signals as simple notification mechanisms that are far more flexible than their hardware siblings. In Linux, Ctrl + C equates to SIGINT (program interrupt), which typically exits a program. It can be stopped, and other functionality such as cleanup can be executed. Ctrl + Z or SIGTSTP (keyboard stop) typically tells a program to be suspended and pushed to the background (more about jobs in a later section), but it can also be blocked—just like SIGINT.
Besides using the keyboard within a program, we can also send signals to programs using the
kill command. The
kill command can kill programs, but these signals can also be used for reloading configurations or sending user-defined signals. The most common signals you may use are SIGHUP (1), SIGINT (2), SIGKILL(9), SIGTERM(15), SIGSTOP(17,18,23), SIGSEGV(12), and SIGUSR1(10)/SIGUSR2(12). The latter two can be defined within your program or leveraged by other developers.
kill command can be used easily as follows:
kill command can refer to the signal number itself or by its name. It does require a process ID number to target. This can easily be found either by searching using
ps | grep X or by using the preceding
Let’s start our activity as follows:
Open a terminal and begin a new script called
mytrap.sh with the following contents:
Execute the script with
$ bash mtrap.sh.
Press Enter several times and watch the behavior of the program.
Press Ctrl + C; notice anything different?
How this script works:
Let’s understand our script in detail:
mytrap.sh script leverages functions and the trap call. Inside of the
setup function, we set the function to be called by the
trap command. Therefore, when Ctrl + C is called, the
cleanup function is executed.
Running the script will cause the script to run forever after printing out the PID of the script.
Pressing regular keys such as Enter will not have an effect on the program.
Pressing Ctrl+C will echo
cleanup on the console and the script will exit using the