setjmp()我已经编写了一个程序来使用and来防止段错误longjmp(),但是我编写的程序可以防止段错误仅发生一次(我在 while 循环中运行我的代码)。
这是我的代码:
#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;
}
输出:
Inside 0 statement
Received SIGSEGV signl
Inside 2 statement
Inside 0 statement
Segmentation fault
预期输出:
Inside 0 statement
Received SIGSEGV signl
Inside 2 statement
.
.(Infinite times)
.
Inside 0 statement
Received SIGSEGV signal
Inside 2 statement
有人可以解释为什么这只是第一次按预期运行吗?另外,我在这里缺少什么来按预期运行我的代码?