首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

setjmp和longjmp用来处理段异常SIGSEGV就成功了,而处理ctrl c中断SIGINT就出错了呢

2012-05-15 
setjmp和longjmp用来处理段错误SIGSEGV就成功了,而处理ctrl c中断SIGINT就出错了呢?下面的代码,我按ctrl c

setjmp和longjmp用来处理段错误SIGSEGV就成功了,而处理ctrl c中断SIGINT就出错了呢?
下面的代码,我按ctrl c和后就弹出一个unknow software exception的错误对话框
#include "stdafx.h"

#include <setjmp.h>  
#include <signal.h>  
#include <stdio.h>  
jmp_buf buf;  
jmp_buf buf2;

void handler(int s)  

  if (s == SIGINT) printf(" now got a SIGINT signal\n");  
  longjmp(buf, 1);  
  /*NOTREACHED*/  
}  

void handler2(int s)
{
if(s==SIGSEGV)printf("now got a SIGSEGV signal\n");
longjmp(buf2,1);
}

int main(int argc, char* argv[])
{

  signal(SIGINT, handler); 
signal(SIGSEGV,handler2);
printf("Ok here!\n");
  if (setjmp(buf))

  printf("back in main\n");  
  return 0;  
  }
else  
  printf("first time through\n"); 

  if (setjmp(buf2))
  printf("back in main\n");  
else  
{
int *p=NULL;
*p=0;


while(1);
return 0;
}

[解决办法]
一般来说,长跳不该这么用。


而是这样:

jmp_buf buf;

if( setjmp(buf) == 0 ) { // try

.... some ....
longjmp(buf, 1); // throw

} else { // catch

.. handle exception 
}

你把这个理解为 try-throw-catch 结构就可以了。




[解决办法]

探讨

一般来说,长跳不该这么用。


而是这样:

jmp_buf buf;

if( setjmp(buf) == 0 ) { // try

.... some ....
longjmp(buf, 1); // throw

} else { // catch

……

热点排行