Signal handler for Unix type platforms
#include stdio.h #include stdlib.h #include signal.h struct sigaction oldHandler; /* A well behaved signal handler */ void mySignalHandler(int sig, siginfo_t *siginfo, void *context) { /* Do processing for passed signal */ ... /* Chain back to old signal handler, to give it a chance to process the signal */ /* Normally this should only be done if the signal was not dealt with by this */ /* signal handler */ if ( oldHandler.sa_flags SA_SIGINFO ) { if ( (oldHandler.sa_sigaction != SIG_DFL) (oldHandler.sa_sigaction != (void (*)(int, siginfo_t *, void *))SIG_IGN) ) { oldHandler.sa_sigaction(sig, siginfo, context); } } else { if ( (oldHandler.sa_handler != SIG_DFL) (oldHandler.sa_handler != SIG_IGN) ) { oldHandler.sa_handler(sig); } } } int main(int argc, char *argv[]) { /* Install mySignalHandler for SIGSEGV */ struct sigaction sigAct; int status; sigAct.sa_handler = 0; /* set to 0 since we are using sa_sigaction */ sigAct.sa_sigaction = mySignalHandler; /* Our signal handler */ sigfillset(&sigAct.sa_mask); /* Disable all signals for our handler */ sigAct.sa_flags = SA_SIGINFO; /* sa_sigaction specifies the handler */ status = sigaction(SIGSEGV, &sigAct, &oldHandler); if (status != 0) { perror("Failed to install handler for signal SIGSEGV"); exit(1); } /* This will invoke the signal handler */ { int *p = (int *)123; *p = 1; } return 0; } |
Signal handler for Windows
#include stdio.h #include stdlib.h #include signal.h void (*oldHandler)(int); /* A well behaved Signal handler */ void mySignalHandler(int sig) { /* Do processing for passed signal */ ... /* Chain back to old signal handler, to give it a chance to process */ /* the signal. Normally this should only be done if the signal */ /* was not dealt with by this signal handler */ if ( oldHandler != SIG_DFL oldHandler != SIG_IGN) { oldHandler(sig); } } int main(int argc, char *argv[]) { /* Install mySignalHandler for signal SIGSEGV */ oldHandler = signal(SIGSEGV, mySignalHandler); if (oldHandler == SIG_ERR) { perror("Failed to install handler for SIGSEGV"); exit(1); } /* This will invoke the signal handler */ { int *p = (int *)123; *p = 1; } return 0; } |
