简体   繁体   中英

Signal system call

I have this code snippet and I even reading about the signal system call a few times, I still do not understand why the program stops the fourth time I press CTRL-C, and not the third. Thanks in advance!

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

int i=0;

void handler(int sig)
{
    i++;
    printf("CTRL-C\n");
    if (i==3)
        signal(SIGINT, SIG_DFL);
}

int main()
{
    signal(SIGINT,handler);
    while (1)
    {
        printf("Hello world!\n");
        sleep(1);
    }

    return 0;
}

I read that the signal system call is not portable, so it may help if I mention I am using the last version of Ubuntu (14.04).

Your custom handler gets called three times. The third time, it registers a new signal handler (namely the default one), which terminates the program the next time the signal is delivered.

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