我正在研究以下代码。程序应该能够用sigaction处理sigint。到目前为止,已经差不多完成了,但我遇到了两个问题。第一个问题是程序应该打印“关闭”并退出状态1,如果它在3秒内接收到3个信号。
第二个问题是我使用gettimeofday和struct timeval来获取与信号到达时间相关的时间(以秒为单位),但是我在这里也失败了。当我尝试它时,我陷入了一个无限循环中,甚至以为我在3秒内按了3次ctrl+c。而且,由此产生的秒数也是相当大的数字。
我希望有人能帮我解决这两个问题。这是密码
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;
}
最佳答案
int timeEnd = t.tv_sec + t.tv_usec;
这不起作用,因为
tv_sec
和tv_usec
是不同的数量级。如果需要微秒精度,则必须将值存储在更大的类型(例如int64_t
)中,并将秒转换为微秒。 if(check if under 3 seconds) { // How to deal with these two problems?
你试过什么?你有几个信号在不同的时间到达,你需要保持一些关于它们的状态,以知道是否所有的信号都在3秒内到达对方。