Reputation: 1153
I have a shell like program which runs in a loop; it accepts few commands and do the required functionality. Program exits only when "getout" command is called.
Let us suppose if a segmentation fault signal is occured, I just handle cleanup my program and instead of exiting the program I just wanted to stay inside. I could acheive this using siglongjmp() call.
My problem: When I run my shell program again in my recover function, and when any segmentation fault is occurred now, my signal is not caught for cleanup and program exits with segmentation fault.
Please suggest a solution:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <setjmp.h>
sigjmp_buf mark;
void myhandler(int signo)
{
my_action();
siglongjmp(mark,-1);
}
recover()
{
my_program_loop();
}
my_program_loop()
{
/* accept some commands and do some functionality*/
/*some part of the code may cause segfault*/
}
main()
{
if (sigsetjmp(mark,0) != 0)
{
printf("siglongjmp() is called\n");
recover();
exit(1);
}
struct sigaction myhandle;
myhandle.sa_handler = myhandler;
sigemptyset(&myhandle.sa_mask);
myhandle.sa_flags = 0;
sigaction(SEGSEGV, &myhandle, NULL);
my_program_loop();
}
Please help.
Upvotes: 4
Views: 4054
Reputation: 23709
You should have a problem with your « my_program_loop », I can catch very well the signal with this code :
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <setjmp.h>
sigjmp_buf mark;
void myhandler(int signo) {
printf("Sig caught\n");
siglongjmp(mark, -1);
}
void my_program_loop(void) {
char *p = NULL;
*p = 5;
}
void recover(void) {
my_program_loop();
}
int main(void) {
struct sigaction myhandle;
if (sigsetjmp(mark, 0) == -1) {
recover();
exit(1);
}
myhandle.sa_handler = myhandler;
sigemptyset(&myhandle.sa_mask);
myhandle.sa_flags = 0;
sigaction(SIGSEGV, &myhandle, NULL);
my_program_loop();
return 0;
}
Upvotes: 3