I have written a program to prevent segfault using setjmp()
and longjmp()
, but the program that I have written prevents segfault from happening only one time (I'm running my code inside a while loop).
Here is my code:
#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
jmp_buf buf;
void my_sig_handler(int sig)
{
if( sig )
{
printf("Received SIGSEGV signl \n");
longjmp(buf,2);
}
}
int main()
{
while( 1)
{
switch( setjmp(buf) ) // Save the program counter
{
case 0:
signal(SIGSEGV, my_sig_handler); // Register SIGSEGV signal handler function
printf("Inside 0 statement \n");
int *ptr = NULL;
printf("ptr is %d ", *ptr); // SEG fault will happen here
break;
case 2:
printf("Inside 2 statement \n"); // In case of SEG fault, program should execute this statement
break;
default:
printf("Inside default statement \n");
break;
}
}
return 0;
}
Output:
Inside 0 statement
Received SIGSEGV signl
Inside 2 statement
Inside 0 statement
Segmentation fault
Expected Output:
Inside 0 statement
Received SIGSEGV signl
Inside 2 statement
.
.(Infinite times)
.
Inside 0 statement
Received SIGSEGV signal
Inside 2 statement
Can someone please explain why this is only running as expected the first time only? Also, what I am missing here to run my code as expected?