#include <signal.h>
typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler)
signal sets the disposition of the signal signum to handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined function (a "signal handler").
NOTE: The signals SIGKILL and SIGSTOP cannot be caught or ignored. The effects of signal system call in a multithreaded process are unspecified.
For more information checkout: man 2 signal
NOTE: The behavior of signal system call varies across different UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction system call instead. Check man 2 signal for detailed information about various portability issues.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
static volatile sig_atomic_t doneflag = 0;
static void setdoneflag(int signo) {
printf("\nIn SignalHandler - setdoneflag\n");
doneflag = 1;
}
int main (void) {
signal(SIGINT, setdoneflag);
while (!doneflag) {
printf("press CTRL+C to kill the Loop\n");
sleep(1);
}
printf("Program terminating ...\n");
return 0;
}
Output:
$ ./a.out
press CTRL+C to kill the Loop
press CTRL+C to kill the Loop
press CTRL+C to kill the Loop
^C
In SignalHandler - setdoneflag
Program terminating ...
$