开发者

Issue with alarm() and SIGALRM in C

I am having an issue with SIGALRM that seems to not be triggered. I am using signal() rather than sigaction() for开发者_JS百科 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜