Handling Termination Signals in Linux Programs
Registering Signal Handlers
In order to handle termination signals in a Linux program, you need to register a signal handler function using the signal()
function. The signal()
function takes two arguments: the signal number and a pointer to the signal handler function.
#include <signal.h>
void signal_handler(int signum) {
// Handle the signal here
}
int main() {
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
// Program logic
return 0;
}
Ignoring Signals
In some cases, you may want to ignore a specific signal. You can do this by setting the signal handler to SIG_IGN
.
#include <signal.h>
int main() {
signal(SIGPIPE, SIG_IGN);
// Program logic
return 0;
}
Blocking Signals
You can also temporarily block signals using the sigprocmask()
function. This can be useful when you need to perform a critical section of code without interruption.
#include <signal.h>
int main() {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigprocmask(SIG_BLOCK, &mask, NULL);
// Critical section
sigprocmask(SIG_UNBLOCK, &mask, NULL);
// Program logic
return 0;
}
Waiting for Signals
Sometimes, you may want to wait for a specific signal to be received. You can use the pause()
function to suspend the execution of the program until a signal is received.
#include <signal.h>
#include <unistd.h>
void signal_handler(int signum) {
// Handle the signal here
}
int main() {
signal(SIGINT, signal_handler);
printf("Waiting for SIGINT signal...\n");
pause();
// Program logic
return 0;
}
By understanding how to handle termination signals in Linux programs, you can write more robust and responsive applications that can gracefully handle exceptional situations and provide a better user experience.