C 中的 Alarm() 和 SIGALRM 问题
我遇到了 SIGALRM 问题,似乎没有被触发。为了简化代码,我使用 signal() 而不是 sigaction() 。
目的是有一些读取的循环,但在 x 秒后,在再次读取之前重新初始化所有变量。我为此使用闹钟。
volatile sig_atomic_t restartBool;
void catch_alarm(int sig)
{
fprintf(stderr, "ALARM CALLED\n");
restartBool = 1;
}
int main(void)
{
int n, fd_in = 0;
char newChar;
signal(SIGALRM, catch_alarm);
while (1) { /* main loop */
restartBool = 0;
// Set a timer before we start reading
alarm(2);
while (restartBool == 0 && (n = read(fd_in, &newChar, 1)) == 1) { /* parse input */
/* ..... */
}
fprintf(stderr, "EXITED THE LOOP");
// Cancel the alarm/timer
alarm(0);
}
}
那么 catch_alarm() 函数中的 fprintf() 语句从未被调用,我不确定为什么(我在 Linux 上运行)。
任何帮助都会很好,
非常感谢,
贾里
I am having an issue with SIGALRM that seems to not be triggered. I am using signal() rather than sigaction() for simplicity of code.
The purpose is to have some loop that reads, but after x seconds, re-initialize all the variables before reading again. I use an alarm for that.
volatile sig_atomic_t restartBool;
void catch_alarm(int sig)
{
fprintf(stderr, "ALARM CALLED\n");
restartBool = 1;
}
int main(void)
{
int n, fd_in = 0;
char newChar;
signal(SIGALRM, catch_alarm);
while (1) { /* main loop */
restartBool = 0;
// Set a timer before we start reading
alarm(2);
while (restartBool == 0 && (n = read(fd_in, &newChar, 1)) == 1) { /* parse input */
/* ..... */
}
fprintf(stderr, "EXITED THE LOOP");
// Cancel the alarm/timer
alarm(0);
}
}
Well the fprintf() statement in the catch_alarm() function is never called, and I am not sure why (I am running on Linux).
Any help would great,
Thank you very much,
Jary
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的读取很可能在计时器关闭之前很久就返回 0(没有剩余字节)。即,循环正在退出,因为您没有数据,然后您正在取消警报(尚未响起)。
It's most likely that your read is returning a 0 (no bytes left) long before your timer goes off. IE, the loop is exiting because you're out of data and then you're cancelling the alarm (which hasn't gone off yet).