What does catching a signal mean in the context of signal handling in Linux? Illustrate with an example how to catch the SIGINT signal using a custom signal handler function.
Catching a signal means responding to a specific signal that has occured in your program. For e.g. suppose you want to catch the signal SIGINT, we can create a custom handler for it and make it perform according to our choice. For e.g.:-
#include <stdio.h> #include <unistd.h> #include <signal.h> void ouch(int sig) { printf("OUCH! - I got signal %d\n", sig); (void) signal(SIGINT, SIG_DFL); } int main() { (void) signal(SIGINT, ouch);
while(1) { printf("Hello World!\n"); sleep(1); } } Here, we are catching the signal SIGINT, whenever that signal occurs i.e. whenever we press ctrl+C,the signal handler, will print OUCH-I got signal 2 and if we press it one more time, the process will terminate.