Tanatos Daniel
Tanatos Daniel

Reputation: 578

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

Upvotes: 0

Views: 227

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476970

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.

Upvotes: 5

Related Questions