When we design a large, complicated script, it is important to consider what happens if the user logs off or shuts down the computer while the script is running. When such an event occurs, a signal will be sent to all affected processes. In turn, the programs representing those processes can perform actions to ensure a proper and orderly termination of the program.
Signals are software interrupts sent to a program to indicate that an important event has occurred. The events can vary from user requests to illegal memory access errors.
To list the signal supported on Linux system:
1 | ## list all signal and corresponding number |
Kill process in command line:
1 | kill -9 <pid> |
Some commonly use signals:
- SIGHUP: Many daemons will
reload
their configuration instead of exiting when receiving this signal, see here for explanation - SIGINT: Issued if the user sends an interrupt signal (Ctrl + C), usually will terminate a program
- SIGQUIT: Issued if the user sends a quit signal (Ctrl + D), it will dump core
- SIGKILL: If a process gets this signal it must quit immediately and will not perform any clean-up operations, this one cannot be ignored or trapped! (这里提一下,force kill会导致程序,比如Python中finally clauses 和 exit handler 无法工作)
- SIGTERM: Software termination signal (sent by kill by default)
- SIGSTOP: Stop process (Ctrl + Z), for example, stop fg mode, see SIGCONT below
- SIGCONT: Continue if stopped, for example, after stop fg mode by (Ctrl + Z), switch to bg will trigger this signal
- SIGSTP: Stop typed at terminal
- SIGCHLD: When a child process stops or terminates, SIGCHLD is sent to the parent process. (这个可以用来trap回收subprocess的资源)
For signal default behavior, see man 7 signal
!!
Note that process cannot define handler for
SIGKILL
andSIGSTOP
, the default behavior is in use.
Note that non-init process cannot ignore
SIGKILL
andSIGSTOP
, they are used for root user and kernel for process management. But, remember, process inD
state is uninterruptable even withSIGKILL
andSIGSTOP
.
Note that you cannot kill init process(PID 1) by
kill -9 1
, this is the exception as described inman 2 kill
: “The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally.” See here for hint.
About trap the signals in script, for example:
1 | ## Set a Trap for Signals for graceful shutdown |
The general format is trap command signals
, for example:
1 | trap "rm -rf /tmp/peek.txt; exit 0" 1 2 |
To ignore signals, for example:
1 | trap "" 2 3 15 |
If main process ignore a signal, all subshells also ignore that signal. However, if you specify an action to be taken on the receipt of a signal, all subshells will still take the default action on receipt of that signal.
Reset the traps to default:
1 | trap 2 3 15 |