开发者

The Unreliable Signal API - Code doesnt work as expected

Basically,expected output of is that it catches KeyboardInte开发者_开发知识库rrupt 5 times and exits the 6th time.(If 1st line of handler() is un-commented)

Now, if i comment that line too, then also the behavior of program doesnt change even though I am using unreliable API.

As I have used signal() function, this is unreliable bcos after the first call to the handler(), SIGINT will then have the default behavior, thats is of exiting the a.out..

The program still quits after 5 ^C.. WHY? **

The code works even without reinstating the handler(). WHy?

**

/* ursig1.c */
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
static int count = 0;
void handler(int signo) {
//  signal(SIGINT,handler);
    /* Re-instate handler */
    ++count;
    /* Increment count */
    write(1,"Got SIGINT\n",11); /* Write message */
}
int
main(int argc,char **argv) {
    signal(SIGINT,handler);
    /* Register function */
    while ( count < 5 ) {
        puts("Waiting for SIGINT..");
        sleep(4);
        /* Snooze */
    }
    puts("End.");
    return 0;
}


Have a read of the Linux man page for signal(2), under the section Portability, where it discusses the varying behaviour of signal(2) across the many different versions of Unix. In particular,

In the original Unix systems, when a handler that was established using signal() was invoked by the delivery of a signal, the disposition of the signal would be reset to SIG_DFL, and the system did not block delivery of further instances of the signal. System V also provides these semantics for signal().

This is the behaviour you are expecting, but it is not what Linux provides, as allowed by POSIX.1. You should be using sigaction(2) to install your signal handlers to get portable and defined behaviour.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜