Imago
Imago

Reputation: 501

sigaction() doesn't catch SIGINT signal

I am currently learning about signals in C and have a small program, that is supposed to not terminate upon receiving the SIGINT signal using sigaction().

The code written below however does terminate, even though it looks fine to me. Maybe I am something missing. Does someone see, why it still terminates?

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

void handle() { printf("%s%d%s", "I won't die....: ", getpid(), "\n"); }

int main() {
  struct sigaction sa;
  sa.sa_handler = handle;
  int k = 0;
  sigaction(SIGINT, &sa, NULL);
  // signal(SIGINT, handle); //signal works just fine

  while (k < 60) {
    printf("%s", "sleeping... \n");
    sleep(1);
    k = k + 1;
  }
}

Additional info: My OS is Windows, however I compile and execute the program in the Bash of a Linux subsystem.

Upvotes: 0

Views: 4928

Answers (1)

Achal
Achal

Reputation: 11921

Open the manual page of sigaction() and understand all the members of struct sigaction and fill all the members of struct sigaction.

struct sigaction {
            void     (*sa_handler)(int);
            void     (*sa_sigaction)(int, siginfo_t *, void *);
            sigset_t   sa_mask;
            int        sa_flags;
            void     (*sa_restorer)(void);
};

Here

struct sigaction sa;

As pointed by @AnttiHaapala here sa is a variable of automatic storage duration and you didn't initialize its members, it invokes undefined behavior as all the other fields contain garbage except sa.sa_handler

So you need to fill the other members of struct sigaction like

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

Or initialize sa itself like

struct sigaction sa = {0};

Also it's not a good practice to write printf() statement inside signal handler, read here How to avoid using printf in a signal handler? .

Upvotes: 2

Related Questions