Today it is recommended to use sigaction .
Moreover, it allows you to automatically reset the signal handler to the default value before your custom handler is called for the first time.
SA_RESETHAND
If set, the signal location should be reset to SIG_DFL and the SA_SIGINFO flag should be cleared when entering the signal handler.
Note: SIGILL and SIGTRAP cannot be automatically reset upon delivery; the system silently applies this restriction.
Otherwise, the location of the signal should not change when entering the signal handler.
In addition, if this flag is set, sigaction() may behave as if the SA_NODEFER flag was also set.
Defining a one-time signal handler
#include <signal.h> #include <stdio.h> action.sa_handler = my_handler; action.sa_flags = SA_RESETHAND; if (sigaction(SIGINT, &action, NULL) == -1) { perror("Failed to install signal handler for SIGINT"); }
source share