Explain how to define and set up a signal handler in C using the signal() function. Provide an example of handling the SIGINT signal and describe what happens when Ctrl+C is pressed.
#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 the ouch function is a custom signal handler, which catches the SIGINT error i.e. ctrl+C, so whenever we will catch ctrl+C, it will print the signal handler statement, otherwise, it will keep printing the while statement. But, since we have added the SIG_DFL flag here, after the first time ctrl+C is pressed, next time whenever we'll press it, it will terminate the process i.e. performing its default behavior.