【发布时间】:2019-10-01 08:03:23
【问题描述】:
我使用setjmp() 和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
有人能解释一下为什么这只是第一次按预期运行吗?另外,我在这里缺少什么来按预期运行我的代码?
【问题讨论】:
-
你调试了吗?为什么会出现分段错误?
-
为什么要重复?分段错误通常是错失编写正确代码的机会。
-
@thebusybee 执行 printf() 时会出现 SEG 错误。但问题的全部要点是控制应该转到开关的情况 2(因为我在收到 SIGSEGV 信号时调用 longjmp())而不是 SEG 故障。
-
那么,您阅读@melpomene 提供的URL 上的注释了吗?在第一个段错误之后,您的程序的行为是未定义。最好的办法是退出程序。
标签: c signals segmentation-fault setjmp