如何将信号处理程序注册为类方法?

e27*_*314 4 c++ signals boost-bind

假设我有class A一个公共方法void f(int sig).在A我的构造函数中添加了

signal(SIGSEV, boost::bind(&A::f, this, _1));
Run Code Online (Sandbox Code Playgroud)

这将返回编译错误

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)'
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?

Mik*_*our 8

作为C函数,signal只能采用普通函数指针,而不是任意可调用类型.您需要一个非成员包装函数和一个要存储的全局变量this,以便从信号处理程序中调用成员函数.

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

// later...
signal_object = this;
signal(SIGSEGV, signal_handler);
Run Code Online (Sandbox Code Playgroud)

  • @LanPac:否,“信号”的处理程序参数必须为函数指针,而“ boost :: bind”的结果为其他值(在这种情况下,包含成员函数指针和其副本的类类型this指针,带有重载的operator()来调用它)。 (2认同)