Home > OS >  cannot catch segmentation fault second time
cannot catch segmentation fault second time

Time:09-23

I'm trying to restart the program when segmention fault occures.

I have following minimal reproducible code:-

#include <csignal>
#include <unistd.h>
#include <iostream>

int app();

void ouch(int sig) {
    std::cout << "got signal " << sig << std::endl;
    exit(app());
}

struct L { int l; };
static int i = 0;

int app() {
    L *l= nullptr;
    while(1) {
        std::cout <<   i << std::endl;
        sleep(1);
        std::cout << l->l << std::endl; //crash
        std::cout << "Ok" << std::endl;
    }
}

int main() {
    struct sigaction act;
    act.sa_handler = ouch;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGKILL, &act, 0);
    sigaction(SIGSEGV, &act, 0);
    return app();
}

It successfully catches sigsegv first time but after it prints 2, it shows me segmentation fault (core dumped)

1
got signal 11
2
zsh: segmentation fault (core dumped)  ./a.out

tested with clang 12.0.1 and gcc 11.1.0 on ArchLinux

Is this operating system specific behavior or is something wrong in my code

CodePudding user response:

The problem is that when you restart the program by calling exit(app()) from inside ouch(), you are still technically inside the signal handler. The signal handler is blocked until you return from it. Since you never return, you therefore cannot catch a second SIGSEGV.

If you got a SIGSEGV, then something really bad has happened, and there is no guarantee that you can just "restart" the process by calling app() again. The best solution to handle this is to have another program start your program, and restart it if it crashed. See this ServerFault question for some suggestions of how to handle this.

  • Related