0

I'm trying to handle some of the C signals in the program I'm writing to add some safety nets in case of accidental closure etc. I've been trying to set up a signal handler for SIGINT using sigaction, and I can see the handler is being called, but it's not stopping the program from being killed anyway.

Trying to use signal with SIG_IGN works fine, however stops me being able to use custom handling. I've tried using signal(...) with my handler, and sigaction(...), and neither are actually working.

void handler(int SIG) {
    //I know this is unsafe just for testing.
    printf("Handled signal %d!\n", SIG); 

    //No actual logic for now.
}

void initializer() {
    //...
    struct sigaction sa;

    sa.sa_handler = handler;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);

    //This doesn't work.
    sigaction(SIGINT, &sa, NULL);

    //This also didn't work.
    // signal(SIGINT, handler);

    //...
}

I believed that handling the signal would stop it by default, and everything I've seen online has indicated this should be enough, but I still receive:

^CHandled signal 2!

And then the process is killed...

SchoolJava101
  • 609
  • 1
  • 5
  • 8
  • 1
    How are you running your process? Please post a *complete* example. Library code can [chain signal handlers...](https://stackoverflow.com/questions/36044772/proper-way-to-chain-signal-handlers-in-linux) Given your user name, you wouldn't be doing this in a JVM process via JNI, would you? – Andrew Henle Aug 22 '19 at 15:20
  • @AndrewHenle It was actually a stupid issue, I was using the code inside a readline loop and using the Ctrl+C combination was making the loop read null and causing the loop to end (so my program was actually ending as expected), and the handler was actually handling SIGINT correctly after all. – SchoolJava101 Aug 22 '19 at 16:56
  • For exact wording: ^C sends an "Interrupt" SIGINT, while "killing" (actually "termination") a program is SIGTERM. The latter is sent when shutting down, for example. Also I guess the read function returned error `EINTR` and not just null. – U. Windl Aug 25 '19 at 23:57

0 Answers0