C Signal Handler

C

Public Domain

A quick demo of how to catch and handle signals in C/C++

Download (right click, save as, rename as appropriate)

Embed

Tags:

c c++ signal
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// signal.c

// A brief demo of how to capture and process signals
// For a full list of Unix Signal Codes see
// http://www.cs.pitt.edu/~alanjawi/cs449/code/shell/UnixSignals.htm

#include <stdio.h>
#include <stdlib.h>		// for exit()
#include <signal.h>		// Signal processing header file
 
/* The signal handler function */
void handler (int signal){
	printf("Caught signal '%d'. Checking what to do with it.\n", signal);
	if (signal == 2){// SIGINT
		printf("Shutting down");
		exit(0);
	}//end if
}//END void handler (int signal)
 
int main (int argc, char ** argv){
	/* Registering the handler, catching
	    SIGINT signals */
	signal( SIGINT, handler );
 
	fprintf (stdout, "Running...\n");
	// Wait for signal (i.e. do nothing)
	while(1){
		// Do nothing
	}//end while

	// We never get here, but it's good form anyway
	return 0;
}//END int main(int argc, char ** argv)