Skip to content

Instantly share code, notes, and snippets.

@sacko87
Last active December 17, 2015 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sacko87/5653642 to your computer and use it in GitHub Desktop.
Save sacko87/5653642 to your computer and use it in GitHub Desktop.
Signal Handling in C $ gcc -Wall -Werror -pedantic -o signal signal.c
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <execinfo.h>
#ifndef ACTION
#define ACTION SIGSEGV
#endif
void action(int signo, siginfo_t *info, void *ptr);
int
main(void)
{
struct sigaction action_n, action_o;
/* setup new handler for action */
action_n.sa_sigaction = action;
sigemptyset(&action_n.sa_mask);
action_n.sa_flags = SA_SIGINFO;
/* get the old handler for action */
sigaction(ACTION, NULL, &action_o);
/* if this is not to be ignored ... */
if(action_o.sa_handler != SIG_IGN)
/* use our new one for the action */
sigaction(ACTION, &action_n, NULL);
/* raise the action to *
* call the handler */
raise(ACTION);
return 0;
}
void
action(int signo, siginfo_t *info, void *ptr)
{
#ifdef __GNUC__
size_t size;
void *stack[10];
#endif
/* string representation of the signal */
fprintf(stderr, "%s\n", strsignal(signo));
#ifdef __GNUC__
/* get the trace and then print it to stderr */
size = backtrace(stack, 10);
backtrace_symbols_fd(stack, size, STDERR_FILENO);
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment