Expert C Programming

(Jeff_L) #1

violation signal\n");


if (s == SIGILL) printf(" now got an illegal


instruction signal\n");


exit(1);


}


main () {


int *p=NULL;


signal(SIGBUS, handler);


signal(SIGSEGV, handler);


signal(SIGILL, handler);


*p=0;


}


Running this program results in this output:


% a.out


now got a segmentation violation signal


Note: this is an example for teaching purposes. Section 7.7.1.1 of the ANSI standard points out that in
the circumstances we have here, the behavior is undefined when the signal handler calls any function
in the standard library such as printf.


Programming Solution


Using setjmp/longjmp to Recover from a Signal


This program uses setjmp/longjmp and signal handling, so that on receiving a control-C
(passed to a UNIX process as a SIGINT signal) the program restarts, rather than quits.


#include <setjmp.h>


#include <signal.h>


#include <stdio.h>


jmp_buf buf;


void handler(int s)


{


if (s == SIGINT) printf(" now got a SIGINT


signal\n");


longjmp(buf, 1);

Free download pdf