C program on How to handle SIGSEGV, but also generate a core dump
By
default, while signal is being handled it is masked, so it can't be triggered
recursively. If masked signal is triggered by program execution (invalid memory
access, segfault, division by 0 etc.), the behavior is undefined:
If
SIGBUS, SIGFPE, SIGILL, or SIGSEGV are generated while they are blocked, the
result is undefined, unless the signal was generated by kill(2), sigqueue(3),
or raise(3).
It
causes process to crash.
With
SA_NODEFER there is no masking, so signal can be handled recursively until
stack overflows. And adding SA_RESETHAND would restore default action (crash
for SIGSEGV).
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
volatile
char *ptr;
static
void signal_handler(int signal)
{
printf("signal handler invoked");
abort(); /* This should give us the
expected core dump (if we survive to this point) */
}
struct
sigaction sa = {};
/* initialised to all zero (I vote for GCC style breach of
standard here) */
int
main()
{
sa.sa_handler = signal_handler;
sa.sa_flags = SA_RESETHAND |
SA_NODEFER; /* To have or have not */
sigaction(SIGSEGV, &sa, NULL);
while(1);
}