Alex Rivera | Logout

Linux C catching kill signal for graceful termination

Asked 2011-09-11T04:02:16.833
20

I have a process using sockets, database connections and the likes. It is basically a server process relaying between sensor data and a web interface, and as such it is important to ensure the application, if killed, terminates gracefully.

How do I handle unexpected exceptions such as segfaults (at least for debugging) as well as kill signals so that I can close any connections and stop any threads running so that the process does not leave a mess of anything it is using?

Edit
Report

1 Answer

10

I sometimes like to get a backtrace on SIGSEGV, the catching part goes like:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void sig_handler(int);

int main() {
    signal(SIGSEGV, sig_handler);
    int *p = NULL;
    return *p;
}

void sig_handler(int sig) {
    switch (sig) {
    case SIGSEGV:
        fprintf(stderr, "give out a backtrace or something...\n");
        abort();
    default:
        fprintf(stderr, "wasn't expecting that!\n");
        abort();
    }
}

You do want to be very careful handling these things, e.g. make sure you can't trigger another signal.

answered 2011-09-11T04:25:14.757

Your Answer