Part 4 of 6 · 2 min read
Uncatchable signals
In plain words: If a program could catch every signal, a buggy or hostile program could refuse to die. The kernel therefore keeps two signals that no program can catch, block or ignore: SIGKILL (number 9) and SIGSTOP (which stops a process until it receives SIGCONT). The kernel carries them out by itself.
A test tries to ignore both:
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
int main(void) {
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
int r1 = sigaction(SIGKILL, &sa, NULL); int e1 = errno;
int r2 = sigaction(SIGSTOP, &sa, NULL);
printf("SIGKILL: %d (%s)\nSIGSTOP: %d (%s)\n", r1, strerror(e1), r2, strerror(errno));
return 0;
}
SIGKILL: -1 (Invalid argument)
SIGSTOP: -1 (Invalid argument)
Both calls failed with the error "Invalid argument".
This explains the habit of system administrators: first send SIGTERM (kill PID), which lets the program clean up and end, and use SIGKILL (kill -9 PID) only if it does not. SIGKILL gives the program no chance to save files or release resources.
A parent can see the difference. The program below forks children that wait, and kills them with SIGTERM and SIGKILL, and also makes one crash with a null write:
SIGTERM: signaled=1 sig=15
null write: sig=11 core=0
SIGKILL: sig=9
The core=0 appears because the test machine does not write core files. On a typical system, signal 11 would also produce one.
Common mistake
Using kill -9 first. The process cannot clean up, so it can leave temporary files, locks and half-written data behind. Send SIGTERM first.
Check yourself:
1. Which two signals cannot be caught?
2. What number did the parent read for a child killed with SIGTERM?
3. Why should SIGTERM be tried first?