Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

c++ - How to Handle SIGABRT signal?

Here is the code on which I set my handler for SIGABRT signal then I call abort() but handler does not get trigered, instead program gets aborted, 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;
}

PROGRAM OUTPUT:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As others have said, you cannot have abort() return and allow execution to continue normally. What you can do however is protect a piece of code that might call abort by a structure akin to a try catch. Execution of the code will be aborted but the rest of the program can 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
";
  }
}    

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

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

int main()
{
  try_and_catch_abort (&do_stuff_aborted);
  try_and_catch_abort (&do_stuff);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...