信号处理程序不起作用 [英] signal handler not working
问题描述
我在我的代码中使用了 czmq
和 zmq
库.我通过在 main 中调用 signal
为 SIGINT
注册了一个信号处理程序.代码如下所示:
I'm using czmq
and zmq
libraries in my code. I've registered a signal handler for SIGINT
by calling signal
in main. The code looks like this:
#include "czmq.h"
void sig_int(int signal);
void* pub_handler(){
zctx_t *context = zctx_new ();
void *publisher = zsocket_new (context, ZMQ_PUB);
zsocket_connect (publisher, "tcp://localhost:5555");
sleep(1);
char topic[20] = "REQ: speedlimit";
// while (true)
{
sleep( randof(10) );
zstr_sendm (publisher, topic);
zstr_send (publisher, "driver analysis data");
}
zctx_destroy (&context);
}
void* sub_handler(){
zctx_t *context = zctx_new();
void *subscriber = zsocket_new (context, ZMQ_SUB);
zsocket_connect (subscriber, "tcp://localhost:5557");
srandom ((unsigned) time (NULL));
char subscription [20] = "RESP: speedlimit" ;
zsocket_set_subscribe (subscriber, subscription);
while (true) {
char *topic = zstr_recv (subscriber);
if(!topic)
break;
char *data = zstr_recv (subscriber);
assert (streq (topic, subscription));
puts (topic);
puts (data);
free (topic);
free (data);
}
zctx_destroy (&context);
}
int main(int argc, const char *argv[])
{
pthread_t pub_id, sub_id;
signal (SIGINT, sig_int);
pthread_create(&pub_id, NULL, pub_handler, NULL);
pthread_create(&sub_id, NULL, sub_handler, NULL);
pthread_join(pub_id, NULL);
pthread_join(sub_id, NULL);
return 0;
}
void sig_int(int signal){
printf (" Interrupted\n");
exit(0);
}
编译为 gcc -o app app.c -lpthread -lczmq -lzmq
.
上述代码在ctrl+c
中断时不会进入信号处理程序.
The above code doesn't get into signal handler when ctrl+c
interrupt is given.
czmq
或 zmq
库有什么问题,应该如何处理?
what is the problem with czmq
or zmq
library and how it should be handled?
推荐答案
zctx 文档 表示 zctx
为 SIGINT
和 SIGTERM
设置了自己的信号处理程序,可能会覆盖您的信号处理程序.
The documentation for zctx says that zctx
sets up its own signal handler for SIGINT
and SIGTERM
, probably overriding your signal handler.
设置信号(SIGINT 和 SIGTERM)处理以便阻塞调用例如 zmq_recv() 和 zmq_poll() 会在用户按下时返回Ctrl-C.
Sets up signal (SIGINT and SIGTERM) handling so that blocking calls such as zmq_recv() and zmq_poll() will return when the user presses Ctrl-C.
它还说 zctx
已被弃用,取而代之的是 zsock
,它似乎没有根据其文档设置信号处理程序.所以我的第一个建议是使用新的 zsock
套接字 API.
It also says that zctx
is deprecated in favor of zsock
, which doesn't appear to setup a signal handler according to its documentation. So my first suggestion is to use the new zsock
socket API.
然而,似乎在这两种情况下你也可以调用 zsys_handler_set(NULL);
(记录在 此处) 以明确禁用 CZMQ 中的默认 SIGINT/SIGTERM 处理.
However, it seems that in both cases you can also call zsys_handler_set(NULL);
(documented here) to explicitly disable the default SIGINT/SIGTERM handling in CZMQ.
PS:printf
不是异步信号安全的,这意味着它不应在信号处理程序中使用.请参阅此处获取异步信号安全函数列表在 POSIX 中.
PS: printf
is not async-signal-safe, meaning that it should not be used in a signal handler. See here for a list of async-signal-safe functions in POSIX.
这篇关于信号处理程序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!