Here is an example of registering a user defined signal handler for the SIGINT signal. Note the signal is sent to a process by typing ctrl-c in the console/window where the process is running.
(source)1 /*------------------------------------------------------------------------ 2 | 3 | File: signal03.c 4 | 5 | Description: This program repeatedly increments a counter. When 6 | overflow occurs, it increments an separate overflow counter. 7 | It has an infinite loop. Typing ctrl-c at the keyboard sends 8 | this process a SIGINT signal. A signal handler, sigint_handler 9 | catches the signal increments a signal counter and prints the 10 | current counts. The signal handler terminates the program when 11 | a maximum number of allowed SIGINT signals have been received. 12 | The user defined sigint_handler function executes instead of 13 | the default handler since sigint_handler is registered as 14 | the handler (the signal function does this). 15 | 16 | 17 | Created: 12 Jan 15 18 | Author: glancast 19 | 20 +-----------------------------------------------------------------------*/ 21 #include <stdio.h> 22 #include <stdlib.h> 23 #include <signal.h> 24 25 const int MAXSIGNALS = 5; 26 27 void sigint_handler(int sig); 28 29 /** 30 * Counters are global so that 31 * the signal handler can access them. 32 */ 33 int cnt = 0; 34 int overflow = 0; 35 int signals = 0; 36 37 38 int main(int argc, char *argv[]) 39 { 40 printf("This program increments a counter. Type ctrl-c to send a SIGINT signal.\n"); 41 printf("%d maximum number of SIGINT signals allowed.\n", MAXSIGNALS); 42 43 signal(SIGINT, sigint_handler); 44 45 while(1) { 46 if (cnt + 1 < cnt) { 47 cnt = 0; 48 overflow++; 49 } else { 50 cnt++; 51 } 52 } 53 54 return 0; 55 } 56 57 58 void sigint_handler(int sig) 59 { 60 signals++; 61 printf("\nsigint %d: overflow = %d, count = %d\n", signals, overflow, cnt); 62 if (signals == MAXSIGNALS) { 63 printf("\nMaximum number of SIGINT signals allowed is %d. Exiting\n", MAXSIGNALS); 64 printf("Edit MAXSIGNALS if you want more!\n\n"); 65 exit(0); 66 } 67 68 }