How to register a signal handler as a class method?

5.9k views Asked by At

Suppose I have a class A, with a public method void f(int sig). In constructor of A I added

signal(SIGSEV, boost::bind(&A::f, this, _1));

This returns compilation error

error : cannot convert `boost::_bi::bind_t<void, boost::_mfi::mf1<void, A, int>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > >' to `__sighandler_t {aka void (*)(int)}' for argument `2' to `void (* signal(int, __sighandler_t))(int)'

Any idea why?

1

There are 1 answers

3
Mike Seymour On BEST ANSWER

Being a C function, signal can only take a plain function pointer, not arbitrary callable types. You'll need a non-member wrapper function, and a global variable to store this, in order to call a member function from a signal handler.

static A * signal_object;
extern "C" void signal_handler(int signum) {signal_object->f(signum);}

// later...
signal_object = this;
signal(SIGSEGV, signal_handler);