【发布时间】:2018-09-23 23:33:54
【问题描述】:
我正在使用 UNIX 和 C++ 中的信号处理并遇到了这个问题。我正在尝试编写一个计数到 10 的程序,每秒一个数字,当用户尝试用 SIGINT(如 CTRL+C)中断它时,它会打印一条消息,告诉它无论如何都会继续计数。
到目前为止,我得到了这个:
#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;
}
现在,我第一次发送中断信号时它工作正常:
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
但是如果我发送一个秒中断信号,进程就会停止。
为什么会这样?我尝试阅读有关“sigaction”的手册,以尝试查看是否有什么东西可以使我创建的处理程序在信号被捕获并回滚到 SIG_DFL 时不会弹出,但无法解决。
谢谢
【问题讨论】:
-
@M.M 是的,解决了它。你想发个帖子让我把它标记为正确吗?
标签: c++ unix system-calls