Redirect c++ crash to stderr

Viewed 313

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 ?

I've tried to search SO for similar answer but I might be just typing the wrong keywords as it seems a common practice.

1 Answers

Matthieu Brucher's comment is correct:

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. If so, you can catch the SIGFPE signal.

#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.

The Linux Programming Interface book also has a pure-C example.


In Windows, you can use Structured Exception Handling (SEH) and the concept is similar (although the functions you need to call are not).


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.

Related