我使用 sigsetjmp 和 siglongjmp 编写了一个分段错误处理程序。一旦它进入信号处理程序,我调用 siglongjmp 以便跳过错误指令。
问题是,我再次想引起 SIGSEGV 并转到同一个处理程序,但现在 sigsetjmp 将返回 1。
如何重置 sigsetjmp?
这是我的代码:
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h>
#include <setjmp.h>
sigjmp_buf env, env1;
void SIGSEGV_handler(int signal)
{
printf("Segmentation fault caught\n");
siglongjmp(env, 1);
}
int main()
{
void * allocation;
size_t size;
static int devZerofd = -1;
struct sigaction sa, sa1;
sa.sa_handler=(void*)SIGSEGV_handler;
sigaction(SIGSEGV, &sa, NULL);
if ( devZerofd == -1 ) {
devZerofd = open("/dev/zero", O_RDWR);
if ( devZerofd < 0 )
perror("open() on /dev/zero failed");
}
allocation = (caddr_t) mmap(0, 5000, PROT_READ|PROT_NONE, MAP_PRIVATE, devZerofd, 0);
if ( allocation == (caddr_t)-1 )
fprintf(stderr, "mmap() failed ");
if ( mprotect((caddr_t)allocation, 5000, PROT_NONE) < 0 )
fprintf(stderr, "mprotect failed");
else
printf("mprotect done: memory allocated at address %u\n",allocation);
if(sigsetjmp(env, 1)==0) {
printf("Causing SIGSEGV: 1\n");
strcpy(allocation,"Hello, how are you");
}
/****** This can't be done again as sigsetjmp won't return 0*****/
/*
if(sigsetjmp(env, 1)==0) {
printf("Causing SIGSEGV: 1\n");
strcpy(allocation,"Hello, how are you");
}
*/
}