[英]Using c++ function pointer as signal handler.
I'd like to add new handler to signal SIGUSR1 in my code. 我想在我的代码中添加新的处理程序来发信号通知SIGUSR1。 here's
signal
signature form header file signal.h
: 这里的
signal
签名表头文件signal.h
:
void (*signal(int, void (*)(int)))(int);
My handler is a member function, so I'm using std::bind
to make the function fit in signal
accepted input. 我的处理程序是一个成员函数,所以我使用
std::bind
来使函数适合signal
接受的输入。
myclass::my_handler(int x);
Here's my conversion of the member function to signal
accepted input: 这是我将成员函数转换为
signal
接受输入:
std::bind(&myclass::my_handler, this, std::placeholders::_1);
However, std::bind
return the c++ representation of function pointer (aka std::function<void(int)>
) and I need the C representation which is (void)(*)(int)
. 但是,
std::bind
返回函数指针的c ++表示(又名std::function<void(int)>
),我需要C表示,它是(void)(*)(int)
。
Should I do the casting forcefully, or perhaps there's c++ alternative for signal
? 我是否应该有力地进行铸造,或者可能有c ++替代
signal
?
Thanks 谢谢
There is no portable way to convert a C++ function to a C function because they can have different ABIs. 没有可移植的方法将C ++函数转换为C函数,因为它们可以具有不同的ABI。
What you can do is this declare a global variable cpphandler as - 你可以做的是将全局变量cpphandler声明为 -
std::function<void(int)> cpphandler = NULL;
Also declare a function as - 同时声明一个函数 -
extern "C" {
void signal_handler(int i);
}
void signal_handler(int i){
cpphandler(i);
return;
}
Now in the function where you want to create the binding do - 现在在你想要创建绑定的函数中 -
cpphandler = std::bind(&myclass::my_handler, this, std::placeholders::_1);
signal(x, signal_handler); //replace x with whatever signal you want to install
This makes sure that the function signal_handler
is created with C ABI. 这确保了函数
signal_handler
是用C ABI创建的。 And calls the C++ function code with C++ ABI. 并使用C ++ ABI调用C ++函数代码。
Now you can use the signal
function with signal_handler
. 现在您可以将
signal
函数与signal_handler
一起signal_handler
。
As you are using a C++ compiler, I suggest that you simply define a normal function that calls your member function handler: 在使用C ++编译器时,我建议您只需定义一个调用成员函数处理程序的普通函数:
void signal_handler_wrapper(int x)
{
myclass::my_handler(x);
}
Then in your main code: 然后在你的主要代码中:
signal(SIGINT, signal_handler_wrapper);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.