Explain how to set up a signal handler using the sigaction function. Provide an example of setting up a handler for the SIGINT signal that blocks the SIGTERM signal during its execution.
#include <stdlib.h> #include <signal.h> #include <unistd.h> void handle_signal(int sig, siginfo_t *info, void *context) { //printf("Caught signal %d from process %d\n", sig, info->si_pid); printf("Caught signal %d from process %d\n", sig, getpid()); } int main() { struct sigaction sa; sa.sa_sigaction = handle_signal; sa.sa_flags = SA_SIGINFO; // Use sa_sigaction instead of sa_handler sigemptyset(&sa.sa_mask); // 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;
}
Here, the my_sigaction function is defined to handle the SIGINT signal and print the signal number and the PID of the sending process. The sa_mask is set to SIGTERM, so that the SIGTERM signal doesn't disturb the signal handler's execution.