|
|
Signals are sent to processes by the UNIX system in response to certain events. Most signals cause the process receiving them to terminate abruptly. However, if you have set a ``trap'' for the signal, you can use them to recover from the emergency. You can also use signals as a means of allowing shell scripts to communicate with other programs running on the system. Note that signal 1 is not a real signal: it is sent by the shell and trapped within the shell for its own purposes.
The following signals are recognized by the shells (although not all of them can be trapped):
Shell signal handling
Value | Signal | Description |
---|---|---|
0 | EXIT | Exit from the shell. |
1 | HUP | A pseudosignal used by the shell, indicating that the standard output has hung up; sending this signal logs you out. |
2 | INT | Sent by a <Del> keystroke; sends an interrupt to the current program. |
3 | QUIT | Sent by a <Ctrl>\ keystroke; causes the current program to abort, leaving behind a core dump (for use in program debugging). |
9 | KILL | Cannot be trapped or ignored; forces the receiving program to die. |
11 | SEGV | Indicates that a segmentation violation (a memory fault within the UNIX system) has occurred. This signal cannot be trapped or ignored by a shell; it invariably terminates the receiving process and causes a core dump. |
15 | TERM | Terminates the receiving program. (This signal should be used in preference to Signal 9, because the receiving program can catch it and carry out some shutdown operation, for example closing open files; Signal 9 forces the process to die immediately.) |
You can use the
trap(M)
command to catch any or all of the trappable signals. Its format is
as follows:
trap command signals_list
In other words, command is executed whenever one of the listed signals (which are specified using the numbers given in the first column of ``Shell signal handling'') is received. For example, if you have a shell script that uses a temporary file called scratchpad, the file will be left behind whenever the script is interrupted, unless you add the following line somewhere near the top of the script:
$ trap "rm scratchpad" 0 1 2 3 15This statement deletes the temporary file whenever an EXIT, HUP, INT, QUIT or TERM signal is received.