mardi 25 juillet 2023

Throwing an Exception from a Signal Handler for Segmentation Fault C++ Linux Debian

I have a requirement to gracefully discard messages if they throw a segmentation fault and continue to listen to the next message in queue. For implementing the same, I have installed a signal handler function for segmentation fault, which throws a runtime exception, and the catch block handles the code for discarding the message.

I have used the compiler flag -fnon-call-exceptions when compiling. I observed that the exception gets caught for some messages but fails sometimes going past the catch block and aborts with the below error.

terminate called after throwing an instance of 'std::runtime_error' what(): Segmentation Fault Aborted (core dumped)

I have also tried adding the jump functions, sigsetjmp and siglongjmp, but it disturbs the flow of code execution and there is an issue when listening to the next message in queue.

I am expecting the code to be able to catch the runtime exception for all messages.

The following is my sample code, which is compiled with the flag -fnon-call-exceptions. It is giving mixed results. Expecting it to work at all times.

#include <iostream>
#include <signal.h>
#include <execinfo.h>
#include <string.h>
//#include <setjmp.h>
 

using namespace std;
void catch_signal(int signalNumber)
{
    throw(10);
}

void testFunc(char* x)
{
    *x = 100;
}
void service_sigset() {
  signal(SIGSEGV, catch_signal);
    try
    {
        testFunc(0);
    }
    catch (int &z)
    {
        cerr << "Caught exception: " << z << endl;
    }
}

int main()
{
    try
    { 
        service_sigset();
    }
    catch(int &z)
    {
        std::cout << "runtime error caught!!!" << std::endl;
    }
    return 0;
}

Can someone please guide me here. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire