简体   繁体   English

将c ++崩溃重定向到stderr

[英]Redirect c++ crash to stderr

Considering a small program like this : 考虑像这样的小程序:

int main()
{
    freopen("./stdout.log", "w", stdout);
    freopen("./stderr.log", "w", stderr);

    int a = 1 / 0;
}

and considering my program is ran by a third party software where I can't change neither how the program is launched nor the environment. 并且考虑到我的程序是由第三方软件运行的,我无法改变程序的启动方式和环境。

How to properly catch the Floating point exception (core dumped) message issued by the division by zero and any other messages that would still be printed on the tty ? 如何正确捕获除以零发出的Floating point exception (core dumped)消息以及仍然打印在tty上的任何其他消息?

I've tried to search SO for similar answer but I might be just typing the wrong keywords as it seems a common practice. 我试图搜索SO以获得类似的答案,但我可能只是键入错误的关键字,因为这似乎是一种常见的做法。

Matthieu Brucher's comment is correct: Matthieu Brucher的评论是正确的:

You need to catch the signals, which is platform dependent. 您需要捕获与平台相关的信号。

From the text of the message, I infer that you may be running on a Linux platform. 从消息文本中,我推断您可能正在Linux平台上运行。 If so, you can catch the SIGFPE signal . 如果是这样,您可以捕获SIGFPE信号

#include <stdexcept>
#include <signal.h>

// compile with -fnon-call-exceptions (for gcc)
signal(SIGFPE, [](int signum) { throw std::logic_error("FPE"); });

The linked answer has some C++ niceties such as using a std::shared_ptr for RAII management of the signal handler and mentions compiler flags needed for gcc to make that work. 链接的答案有一些C ++细节,例如使用std::shared_ptr进行信号处理程序的RAII管理,并提到gcc使其工作所需的编译器标志。

The Linux Programming Interface book also has a pure-C example . Linux编程接口书也有一个纯C示例


In Windows, you can use Structured Exception Handling (SEH) and the concept is similar (although the functions you need to call are not). 在Windows中,您可以使用结构化异常处理(SEH) ,概念类似(尽管您需要调用的函数不是)。


Note that in either case you're relying on platform-specific behavior not specified by C++ (division by zero is undefined behavior) so obviously this will not result in portable code. 请注意,在任何一种情况下,您都依赖于C ++未指定的特定于平台的行为(除以零是未定义的行为),因此显然这不会导致可移植代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM