Reputation: 369
I'd like to call a function before processing the stop/kill signal.
Is there an easy way to do this?
Upvotes: 1
Views: 299
Reputation: 122381
You can handle a SIGTERM
and SIGINT
signal by setting-up a signal handler (see signal(3)
), however you cannot handle SIGKILL
, which is why it should be the last resort to use against a program.
If you always want to do something before the process exits, then see atexit(3)
.
$ cat sig.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
static void closedown() {
printf("running closedown\n");
}
static void sighandler(int signal) {
exit(1);
}
int main(int argc, const char **argv) {
signal(SIGTERM, sighandler);
signal(SIGINT, sighandler);
atexit(closedown);
while (1) {
sleep(1);
printf("tick\n");
}
return 0;
}
$ clang -o sig sig.c
$ ./sig
tick
tick
^Crunning closedown
Upvotes: 5