gpt4 book ai didi

c++ - 为什么我的信号处理程序只执行一次?

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:19 24 4
gpt4 key购买 nike

我正在研究 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,但无法解决。

谢谢

最佳答案

您可以在每次发送信号时重置信号处理程序。我已经看到这个用于在可能反复预期信号时处理 SIGUSR。

#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;
}

关于c++ - 为什么我的信号处理程序只执行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52471162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com