c++ SIGTERM 捕获后不返回
我试图在我的程序中捕获 SIGTERM,这就是问题所在。
我的程序启动并设置信号 SIGTERM 的侦听器。然后程序进入一个循环,该循环使用 select 不断检查套接字文件描述符,以便它是非阻塞的。当我通过 Kill 发送程序 TERM 时,程序确认它收到了信号,但这就是它不会返回到我之前描述的循环。
信号处理程序在类内设置一个公共变量,以便循环知道退出。我应该提到的是,在 gdb 中这是有效的,但在 gdb 之外却不起作用。
提前致谢。
class A
{
public:
bool volatile stop;
void loop();
{
while(!stop)
{
//check socket
}
}
};
A *aptr;
void sigterm_handler(int i)
{
aptr->stop = true;
}
int main()
{
A a;
aptr = &a;
struct sigaction sa;
sa.sa_handler = &sigterm_handler;
sigaction(SIGTERM, &sa, NULL);
a.stop = false;
a.loop();
}
编辑:抱歉没有正确完成代码。
I am trying to catch SIGTERM in my program, this is the problem.
My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.
The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.
Thanks in advance.
class A
{
public:
bool volatile stop;
void loop();
{
while(!stop)
{
//check socket
}
}
};
A *aptr;
void sigterm_handler(int i)
{
aptr->stop = true;
}
int main()
{
A a;
aptr = &a;
struct sigaction sa;
sa.sa_handler = &sigterm_handler;
sigaction(SIGTERM, &sa, NULL);
a.stop = false;
a.loop();
}
EDIT: sorry did not finish the code off properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使 stop “易失性”,否则编译器实际上不会在循环中检查它,因为它认为它无法更改。
You need to make stop "volatile" otherwise the compiler won't actually check it in the loop as it thinks it can't change.
也许这与 struct sigaction 中其他未初始化的成员有关。
gdb
可能会将内存初始化为 0,但没有gdb
则不会初始化。Maybe this is related with the other members of
struct sigaction
that are not initialized.gdb
maybe initializes the memory to 0, whereas it is not initiazlized withoutgdb
.正如上面提到的,挥发性是正确的答案。另外我想补充一点,根据您的代码 sigwait() 将是更好的解决方案,而不是循环...顺便说一句,如果 sigwait 您不需要信号处理程序
Opps,抱歉错过了套接字操作
As was mentioned above volatile is the correct answer. Also I'd like to add that according to you code sigwait() will be better solution instead the loop... BTW in case of sigwait you do not need signal handler
Opps, sorry miss a socket operations
您可能会发现任何信号(尤其是 SIGTERM)都会终止您在 while 循环内执行的任何系统调用。我所说的“系统调用”是指从套接字读取、选择或连接的任何操作。
查看这篇文章。
另请检查示例测试程序。
You might find that any signal (especially SIGTERM) will terminate any system calls you are doing inside the while loop. And by "system calls" I mean anything that reads from or does select or connect on a socket.
Check out this write up.
Also check the example test program.