In C++11, how can I immediately leave a function when a signal is caught?
c++, c++11, exception, multithreading
Solution
You can't portablely throw an exception from a signal handler.
Not all OS actually have the appropriate stack-frame in place that is needed for stack unwinding. The best you can do is set a flag then test for this in your application.
To prevent you speckling your code with tests. You could mkae your application into a `Reactor` then register the actual work with the reactor. Before the reactor does a new piece of work it tests to see if the signal flag has been set.
Reactor workList;
workList.add(&callee1);
workList.add(&callee2);
workList.run();
Then inside the `Reactor`;
while(notSignalled() && !list.empty());
{
list.head().run();
}
Problem
In a C++11 program, I have a few functions that must stop as soon as possible (and return to the caller) every time a given unix signal is received. At first glance, an exception, thrown when the signal is received and intercepted only in the caller function, seems to be the obvious solution. ``` void sighandler(int sig) { throw new myexc(); } void caller(void) { try { callee1(); callee2(); } catch (myexc e) { ... } } ``` But safe, portable signal-handling is rather limited as changing the value of a volatile sig_atomic_t seems to be the only correct thing to do in a signal handler. But I don't want to have my code littered with tests checking whether the sig_atomic_t has changed or not. ``` void sighandler(int sig) { vol = 1; } void callee1(void) { do_stuff(); if (vol == 1) return; do_other_stuff(); if (vol == 1) return; do_something_again(); ... } ``` Having a thread waiting for the value being changed then throwing an exception to be caught by the other thread does not seem to be a valid solution either. How could I do this in a safe, portable and elegant way ?