c ++中止覆盖 [英] c++ abort override

查看:257
本文介绍了c ++中止覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些C ++库在出现错误的情况下调用abort()函数(例如SDL)。在这种情况下,没有提供有用的调试信息。无法捕获中止呼叫并写入一些诊断日志输出。我想覆盖这种行为,而不会重写/重建这些库。我想抛出异常并处理它。

解决方案

请注意, abort 引发 SIGABRT 信号,好像它调用 raise(SIGABRT)。您可以在这种情况下安装一个被调用的信号处理程序,如下所示:

  #include< signal.h> 

externCvoid my_function_to_handle_aborts(int signal_number)
{
/ *你的代码到这里。您可以输出调试信息。
如果从这个函数返回,并且调用
,因为abort()被调用,你的程序将退出或崩溃
(在Windows上有一个对话框)。
* /
}

/ *尽早在程序的初始化* /
信号(SIGABRT,& my_function_to_handle_aborts)中执行此操作;

如果您无法阻止 abort 电话(比如,尽管你最好的意图,它们是由于蠕虫而引起的),这可能会让你收集一些更多的调试信息。这是便携式ANSI C,所以它在Unix和Windows以及其他平台上也起作用,但是在中止处理程序中所做的工作通常不会被移植。请注意,当 assert 失败或甚至其他运行时功能 - 也就是说,如果 malloc 检测到堆腐败所以你的程序在这个处理程序中可能处于疯狂的状态。你不应该分配内存 - 如果可能的话使用静态缓冲区。只需尽量少的收集您需要的信息,向用户收到错误消息,然后退出。



某些平台可能允许他们的中止功能进一步定制。例如,在Windows上,Visual C ++有一个功能 _set_abort_behavior ,您可以选择是否向用户显示消息,以及是否收集故障转储。


Some C++ libraries call abort() function in the case of error (for example, SDL). No helpful debug information is provided in this case. It is not possible to catch abort call and to write some diagnostics log output. I would like to override this behaviour globally without rewriting/rebuilding these libraries. I would like to throw exception and handle it. Is it possible?

解决方案

Note that abort raises the SIGABRT signal, as if it called raise(SIGABRT). You can install a signal handler that gets called in this situation, like so:

#include <signal.h>

extern "C" void my_function_to_handle_aborts(int signal_number)
{
    /*Your code goes here. You can output debugging info.
      If you return from this function, and it was called 
      because abort() was called, your program will exit or crash anyway
      (with a dialog box on Windows).
     */
}

/*Do this early in your program's initialization */
signal(SIGABRT, &my_function_to_handle_aborts);

If you can't prevent the abort calls (say, they're due to bugs that creep in despite your best intentions), this might allow you to collect some more debugging information. This is portable ANSI C, so it works on Unix and Windows, and other platforms too, though what you do in the abort handler will often not be portable. Note that this handler is also called when an assert fails, or even by other runtime functions - say, if malloc detects heap corruption. So your program might be in a crazy state during that handler. You shouldn't allocate memory - use static buffers if possible. Just do the bare minimum to collect the information you need, get an error message to the user, and quit.

Certain platforms may allow their abort functions to be customized further. For example, on Windows, Visual C++ has a function _set_abort_behavior that lets you choose whether or not a message is displayed to the user, and whether crash dumps are collected.

这篇关于c ++中止覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆