【发布时间】:2013-12-21 13:18:52
【问题描述】:
我正在编写以下代码。该程序应该能够使用 sigaction 处理 SIGINT。到目前为止,它几乎完成了,但我遇到了两个问题。
第一个问题是如果在 3 秒内收到 3 个信号,程序应该打印“正在关闭”并以状态 1 退出。
第二个问题是我正在使用 gettimeofday 和 struct timeval 来获取有关信号到达时间的时间(以秒为单位),但我在这里也失败了。当我尝试它时,我陷入了一个无限循环,甚至以为我在 3 秒内按了 ctrl + C 3 次。此外,由此产生的秒数是相当大的数字。
我希望有人可以帮助我解决这两个问题。这是代码
int timeBegin = 0;
void sig_handler(int signo) {
(void) signo;
struct timeval t;
gettimeofday(&t, NULL);
int timeEnd = t.tv_sec + t.tv_usec;
printf("Received Signal\n");
int result = timeEnd - timeBegin;
if(check if under 3 seconds) { // How to deal with these two problems?
printf("Shutting down\n");
exit(1);
}
timeBegin = timeEnd // EDIT: setting the time new, each time when a signal arrives. Is that somehow helpful?
}
int main() {
struct sigaction act;
act.sa_handler = &sig_handler;
sigaction(SIGINT, &act, NULL);
for( ;; ) {
sleep(1);
}
return 0;
}
【问题讨论】:
标签: c linux signals handler sigint