How to handle a SIGABRT signal?

Here is the code on which I set the handler for the signal SIGABRT, then I call abort(), but the handler does not receive a trigger, and the program is interrupted, why?

#include <iostream>
#include <csignal>
using namespace std;
void Triger(int x)
{
    cout << "Function triger" << endl;
}

int main()
{
    signal(SIGABRT, Triger);
    abort();
    cin.ignore();
    return 0;
}

SOFTWARE OUTPUT:

enter image description here

+7
source share
3 answers

As others have said, you cannot get abort () to return and allow execution to continue normally. However, you can protect a piece of code that might cause an interrupt with a structure similar to a catch attempt. Code execution will be interrupted, but the rest of the program may continue. Here is a demo:

#include <csetjmp>
#include <csignal>
#include <cstdlib>
#include <iostream>

jmp_buf env;

void on_sigabrt (int signum)
{
  signal (signum, SIG_DFL);
  longjmp (env, 1);
}

void try_and_catch_abort (void (*func)(void))
{
  if (setjmp (env) == 0) {
    signal(SIGABRT, &on_sigabrt);
    (*func)();
    signal (SIGABRT, SIG_DFL);
  }
  else {
    std::cout << "aborted\n";
  }
}    

void do_stuff_aborted ()
{
  std::cout << "step 1\n";
  abort();
  std::cout << "step 2\n";
}

void do_stuff ()
{
  std::cout << "step 1\n";
  std::cout << "step 2\n";
}    

int main()
{
  try_and_catch_abort (&do_stuff_aborted);
  try_and_catch_abort (&do_stuff);
}
+14
source

SIGABRT, abort() , , . C99 7.20.4.1, 2:

, SIGABRT , ....

, , .

+7

You get these symptoms, that is, a pop-up debugging dialog when you have a debug build (with windows and Visual Studio - I'm testing the 2012 version), because it sets up a debugging gap in the abort () debugging implementation). If you select "ignore", you will get this message "Function triger"

If you are creating a release, then you will not get a debug popup dialog and you will get a message as expected

+2
source

All Articles