CrazyLion
CrazyLion

Reputation: 25

about SIGALRM and alarm

There is something really puzzles me,the core codes is followed

    char buffer[MAX_BUFFER+1];
    int ret;
    signal(SIGALRM,wakeup);
    printf("You have 3 seconds to enter the password\n");
    alarm(3);
    ret=read(0,buffer,MAX_BUFFER);
    alarm(0);

Could you tell me why there needs seconds alarm(0) here , what is this meaning?thank you!!!

Upvotes: 0

Views: 1345

Answers (1)

paxdiablo
paxdiablo

Reputation: 882466

It's there because you may enter the password in two seconds (for example), so you don't want an alarm going off one second after that. In other words, it turns off the alarm in the case where the thing you're trying to timeout actually finishes before the timeout occurs.

Doing an alarm(0) when no current alarm is active is harmless (other than the other problems such as interference with sleep and so on, but they're unimportant here).

However, having a rogue SIGALRM delivered when you're not expecting it may well cause some damage (such as if you've reset the SIGALRM handler to something else) so it's safer to disable it anyway, even if it's expired.

Upvotes: 5

Related Questions