Custom SIGINT signal handler - the program still exits even after the signal is caught

I am playing with libraries signal.h

and unistd.h

, and I am having some problems. In the code below, when I send a signal SIGINT

to my current program by calling CTRL-C

, the signal is caught. However, pressing it again CTRL-C

ends the program. As I understand it, the print expression "Received signal 2"

should print every time I click CTRL-C

.

Is my understanding of this signal wrong or is there a bug in my code?

Thanks for your input!

#include "handle_signals.h"


void sig_handler(int signum)
{
    printf("\nReceived signal %d\n", signum);
}

int main()
{
    signal(SIGINT, sig_handler);
    while(1)
    {
        sleep(1);
    }
    return 0;
}

      

Terminal output:

xxx@ubuntu:~/Dropbox/xxx/handle_signals$ ./handle_signals 
^C
Received signal 2
^C
xxx@ubuntu:~/Dropbox/xxx/handle_signals$ 

      

Edit: here is the header I included

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


void sig_handler(int signum);

      

Thank you for your responses. Read them now!

+3


source to share


2 answers


Don't use signal

, use sigaction

:

Signal () behavior varies across UNIX versions and has also historically varied across Linux versions. Avoid using: use sigaction (2) instead.

http://man7.org/linux/man-pages/man2/signal.2.html



On original UNIX systems, when a handler that was set using signal () was called by delivering a signal, the signal location will be reset to SIG_DFL and the system will not block delivery of further instances of the signal.

Linux implements the same semantics: a reset handler when a signal is sent.

+4


source


The behavior signal

after receiving the first signal depends on different implementations. It is usually necessary to reinstall the handler after receiving a signal as the handler is reset to its default action:

void sig_handler(int signum)
{  
    signal(SIGINT, sig_handler);
    printf("\nReceived signal %d\n", signum);
}

      



which is one of the reasons you should no longer use signal

and use sigaction

. You can see an example here using sigaction .

+2


source







All Articles