如何在前 50 秒忽略信号
How to ignore signal for first 50 seconds?
本文关键字:信号 更新时间:2023-10-16
void signal_handler(int signo)
{
struct sigaction act;
if ((sigaction(signo, NULL, &act) == -1) || (act.sa_handler != SIG_IGN))
{
alarm(50);
}
}
int main()
{
sigaction(SIGINT,signal_handler);
sigaction(SIGALAM,signal_handler);
alarm(50);
while (1)
{
}
return 0;
}
我想在前 50 秒忽略 Ctrl + C 信号。我用警报尝试了它,但它并没有忽略信号。
这些是实现目标需要遵循的步骤:
- 将
SIGINT
设置为main
启动时SIG_IGN
。 - 然后将
SIGALARM
设置为调用其他处理程序(50 秒后)。 - 在该处理程序中,更改
SIGINT
以便它现在指向实际处理程序。
这应该在前五十秒左右忽略SIGINT
中断,然后对它们进行操作。
这是一个完整的程序,展示了这一点。它基本上执行上面详述的步骤,但对测试程序稍作修改:
- 开始忽略
INT
. - 将
ALRM
设置为在十秒后激活。 - 开始每秒生成
INT
信号,持续 20 秒。 - 激活警报后,停止忽略
INT
。
该程序是:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
static time_t base, now; // Used for tracking time.
// Signal handlers.
void int_handler(int unused) {
// Just log the event.
printf(" - Handling INT at t=%ldn", now - base);
}
void alarm_handler(int unused) {
// Change SIGINT handler from ignore to actual.
struct sigaction actn;
actn.sa_flags = 0;
actn.sa_handler = int_handler;
sigaction(SIGINT, &actn, NULL);
}
int main(void)
{
base = time(0);
struct sigaction actn;
// Initially ignore INT.
actn.sa_flags = 0;
actn.sa_handler = SIG_IGN;
sigaction(SIGINT, &actn, NULL);
// Set ALRM so that it enables INT handling, then start timer.
actn.sa_flags = 0;
actn.sa_handler = alarm_handler;
sigaction(SIGALRM, &actn, NULL);
alarm(10);
// Just loop, generating one INT per second.
for (int i = 0; i < 20; ++i)
{
now = time(0);
printf("Generating INT at t=%ldn", now - base);
raise(SIGINT);
sleep(1);
}
return 0;
}
这是我盒子上的输出,所以你可以看到它在运行,在前十秒忽略INT
信号,然后对它们采取行动:
Generating INT at t=0
Generating INT at t=1
Generating INT at t=2
Generating INT at t=3
Generating INT at t=4
Generating INT at t=5
Generating INT at t=6
Generating INT at t=7
Generating INT at t=8
Generating INT at t=9
Generating INT at t=10
- Handling INT at t=10
Generating INT at t=11
- Handling INT at t=11
Generating INT at t=12
- Handling INT at t=12
Generating INT at t=13
- Handling INT at t=13
Generating INT at t=14
- Handling INT at t=14
Generating INT at t=15
- Handling INT at t=15
Generating INT at t=16
- Handling INT at t=16
Generating INT at t=17
- Handling INT at t=17
Generating INT at t=18
- Handling INT at t=18
Generating INT at t=19
- Handling INT at t=19
相关文章:
- Qt VTK交互风格的信号到小部件
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何在没有信号的情况下从C++执行QML插槽
- 线程之间的布尔停止信号
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 有可能在信号处理程序中设置promise吗
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 在条件变量中触发错误信号的频率是多少
- 在信号处理程序中捕获C++未处理的异常并恢复应用程序
- 调试和自由执行中的信号处理
- 升压信号2将插槽传递到成员功能以断开连接
- C++函数包装器来捕获某些信号
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 中止信号来自 C++ 中的中止(3) (SIGABRT)
- Qt将信号与另一个类方法连接
- C++ 信号和插槽不工作:插槽不响应事件
- Coursera :自动评分器的未知信号 11
- 阻塞信号会导致升压过程不起作用