6. Practical Signal Handling with signal() Function
Describe how the signal() function works in setting up a signal handler in a C program. Provide a brief example of how to use signal() to catch the SIGINT signal (generated by typing Ctrl+C) and handle it with a custom function. What are the possible return values of the signal() function and their significance?
The signal function has the following prototype : sighandler_t signal(int signum, sighandler_t handler);
here signum is the number of the signal to catch and handler is the function to be called when that signal is catched.
For e.g.:-
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> void handle_signal(int sig) { printf("Caught signal %d\n", sig); } int main() { // Set up the signal handler signal(SIGINT, handle_signal); // Loop indefinitely while (1) { printf("Running...\n"); sleep(1); } return 0; }
The signal function returns previous value of the signal handler, or SIG_ERR on error. When an error occurs errno is specified with it which indicates the reason for error.