简体   繁体   中英

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".

alarm(1) will eventually be executed only one time in this case. 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. 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.

Ie, the alarm gets cleared in each iteration of the loop. And since your loop runs forever, the alarm is never permanently set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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