Check out this program. It sets a signal handler for SIGTERM so that when it receives a SIGTERM the message "Got SIGTERM" is printed and it kills itself afterwards.
Code:
#define _POSIX_C_SOURCE 200809L
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
static void handle(int signal) {
char msg[] = "Got SIGTERM\n";
(void) write(1, msg, sizeof msg);
(void) raise(signal);
}
int main(void) {
// Define sigaction structure
struct sigaction sa;
sa.sa_handler = handle; // Signal handler
if (sigemptyset(&sa.sa_mask) == -1) { // Mask
(void) fputs("Couldn't set signal mask.\n", stderr);
return 1;
}
/* Reset actions when the singal handler is called, so that when the process
kills itself with raise() default actions are taken */
sa.sa_flags = SA_RESETHAND;
// Set signal handler for SIGTERM
if (sigaction(SIGTERM, &sa, (struct sigaction *)0) == -1) {
(void) fputs("Couldn't set signal handler.\n", stderr);
return 1;
}
(void) printf("Send SIGTERM to PID: %ji\n", (intmax_t)getpid());
(void) getchar();
return 0;
}
The examples I've seen so far set the mask of the structure with sigemptyset(), that's why I used it. It does the following:
sigemptyset - initialize and empty a signal set
The
sigemptyset() function initializes the signal set pointed to by
set, such that all signals defined in POSIX.1-2017 are excluded.
So far so good. But then I checked what that mask is all about, and it says:
The <signal.h> header shall declare the sigaction structure, which shall include at least the following members:
[...]
sigset_t sa_mask Set of signals to be blocked during execution of the signal handling function.
So does that mean that if I set the same handler for another signal, if during the execution of the signal handler another signal is received, the handler would be called again because no signals are blocked???? That's certainly not what I want. I want the signal handler to be called just one whatever signal caused it and block the rest of the pending signals.