Explain how to block signals during the execution of a signal handler using the sigaction structure. Provide an example of blocking SIGTERM while handling SIGINT.
Signals can be blocked while a signal handler is being executed by specifying them in the sa_mask field. This prevents the specified signals from being interrupted by the handler. For e.g.: -
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include<unistd.h> void my_sigaction(int signum, siginfo_t *info, void *context) { printf("Caught signal %d, sent by process %d\n", signum, info->si_pid); } int main() { struct sigaction sa; sa.sa_sigaction = my_sigaction; sa.sa_flags = SA_SIGINFO; // Use sa_sigaction instead of sa_handler sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGTERM); // Block SIGTERM while handling SIGINT // Set up the signal handler for SIGINT if (sigaction(SIGINT, &sa, NULL) == -1) { perror("sigaction"); exit(EXIT_FAILURE); } // Loop indefinitely while (1) { printf("Running...\n"); sleep(1); } return 0; }