c++ - 如何处理SIGABRT信号?

标签 c++ signals

这是我为 SIGABRT 信号设置我的处理程序的代码,然后我调用 abort() 但处理程序没有被触发,而是程序被中止,为什么?

#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;
}

程序输出:

enter image description here

最佳答案

正如其他人所说,您不能让 abort() 返回并允许执行正常继续。但是,您可以做的是通过类似于 try catch 的结构保护一段可能调用中止的代码。代码的执行将被中止,但程序的其余部分可以继续。这是一个演示:

#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);
}

关于c++ - 如何处理SIGABRT信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934879/

相关文章:

C++ 从栈中获取指针

python - 如果忽略 SIGCHLD,Firefox Webdriver 将无法工作

c - 如何在 ANSI C 中使用 strsignal 和 WCOREDUMP?

linux - 在 Linux 下,被忽略的信号是否仍会中断系统调用?

不能捕获多个中断

c++ - 如何获取 llvm 内联 asm 操作数类型?

c++ - QChar::isLetterOrNumber() 失败

c++ - 创建一个 2 行(不换行)的 QPushButton

python - 是否可以安全地监控生产 Linux 系统上的 Python 堆栈?

c++ - 重写 delete[] 运算符?