为什么我的信号处理程序只执行一次? [英] Why does my signal handler only execute once?
问题描述
我正在研究 UNIX 和 C++ 中的信号处理,但遇到了这个问题.我正在尝试编写一个计数到 10 的程序,每秒一个数字,当用户尝试用 SIGINT(如 CTRL+C)中断它时,它会打印一条消息,告诉它无论如何都会继续计数.
I'm playing with signal handling in UNIX and C++ and came across with this issue. I'm trying to write a program that counts to 10, one number per second, and when the user tries to interrupt it with a SIGINT (like CTRL+C) it prints a message telling it it will continue to count no matter what.
到目前为止,我得到了这个:
So far, I got this:
#include <iostream>
#include <signal.h>
#include <zconf.h>
using namespace std;
sig_atomic_t they_want_to_interrupt = 0;
void sigint_handler(int signum) {
assert(signum == SIGINT);
they_want_to_interrupt = 1;
}
void register_handler() {
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGINT);
sa.sa_handler = sigint_handler;
sigaction(SIGINT, &sa, 0);
}
int main() {
register_handler();
cout << "Hi! We'll count to a hundred no matter what" << endl;
for (int i = 1; i <= 100; i++) {
if (they_want_to_interrupt == 1) {
cout << endl << "DON'T INTERRUPT ME WHILE I'M COUNTING! I'll count ALL THE WAY THROUGH!!!" << endl;
they_want_to_interrupt = 0;
}
cout << i << " " << flush;
sleep(1);
}
cout << "Done!" << endl;
return 0;
}
现在,我第一次发送中断信号时它正常工作:
Now, the first time around I send the interrupt signal it works properly:
Hi! We'll count to a hundred no matter what
1 2 ^C
DON'T INTERRUPT ME WHILE I'M COUNTING! I'll count ALL THE WAY THROUGH!!!
3 4
但是如果我发送一个second中断信号,进程就会停止.
But if I send a second interrupt signal, the process is stopped.
为什么会这样?我尝试阅读有关sigaction"的手册,以尝试查看是否有某些内容可以使我创建的处理程序在信号被捕获并回滚到 SIG_DFL 时不会弹出,但无法解决.
Why does it happen? I tried reading the manual on ´sigaction´ to try to see if there's something that will make the handler I created not be popped when the signal is caught and roll back to SIG_DFL, but couldn't work it out.
谢谢
推荐答案
您可以在每次发送信号时重置信号处理程序.我已经看到这是在可能重复预期信号时处理 SIGUSR 的方法.
You can just reset the signal handler each time a signal is sent. I've seen this for handling SIGUSR when a signal might be expected repeatedly.
#include <iostream>
#include <cassert>
#include <signal.h>
#include <zconf.h>
using namespace std;
void register_handler();
sig_atomic_t they_want_to_interrupt = 0;
void sigint_handler(int signum) {
assert(signum == SIGINT);
they_want_to_interrupt = 1;
register_handler();
}
void register_handler() {
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGINT);
sa.sa_handler = sigint_handler;
sigaction(SIGINT, &sa, 0);
}
int main() {
register_handler();
cout << "Hi! We'll count to a hundred no matter what" << endl;
for (int i = 1; i <= 100; i++) {
if (they_want_to_interrupt == 1) {
cout << endl << "DON'T INTERRUPT ME WHILE I'M COUNTING! I'll count ALL THE WAY THROUGH!!!" << endl;
they_want_to_interrupt = 0;
}
cout << i << " " << flush;
sleep(1);
}
cout << "Done!" << endl;
return 0;
}
这篇关于为什么我的信号处理程序只执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!