简体   繁体   English

alarm(int)在while循环中不起作用

[英]alarm(int) doesn't work in a while loop

I'm trying to execute this code: 我正在尝试执行以下代码:

signal(SIGALRM,handler);
alarm(1);
while(1){}

The handler function just prints "test". handler函数仅打印“测试”。

alarm(1) will eventually be executed only one time in this case. 在这种情况下, alarm(1)最终将仅执行一次。 I tried to put it in the loop and it seems that it doesn't get executed at all! 我试图将其放入循环中,似乎根本没有执行!

I am kinda new to signals. 我对信号有点陌生。 Can someone explains to me how this happens? 有人可以向我解释这是怎么发生的吗?

If you just put alarm(1) in the loop in your example, you'll call alarm(1) infinitely many times within a few microseconds of each invocation. 如果在示例中将alarm(1)放入循环中,则每次调用后几微秒内将无限次调用alarm(1) And then this happens: 然后发生这种情况:

If an alarm has already been set with alarm() but has not been delivered, another call to alarm() will supersede the prior call. 如果已使用alarm()设置了警报但尚未传递警报,则对alarm()的另一个调用将取代先前的调用。

Ie, the alarm gets cleared in each iteration of the loop. 即,在循环的每次迭代中都会清除警报。 And since your loop runs forever, the alarm is never permanently set. 而且由于您的循环永远运行,因此警报永远不会永久设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM