Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1544126
  • 博文数量: 237
  • 博客积分: 5139
  • 博客等级: 大校
  • 技术积分: 2751
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-18 14:48
文章分类

全部博文(237)

文章存档

2016年(1)

2012年(4)

2011年(120)

2010年(36)

2009年(64)

2008年(12)

分类: C/C++

2010-11-11 17:48:44

/* -------------------------------------------------------------------------
** File : cexcept.c *
** Coder: Spark Song. *
** Note : Use the example code from 《C Interfaces and Implementations》 *
** -------------------------------------------------------------------------
*/


#include
#include
#include
#include

int
Allocation_handled = 0;
jmp_buf Allocate_Failed;

void
*allocate(unsigned n)
{

void
* p = (void *)malloc(n);

if
(p)
return
p;

if
(Allocation_handled) /* 如果实例化了异常处理程序的话... */
longjmp(Allocate_Failed, 1); /* 产生异常,并抛出 */

assert(0); /* 如果没有实例化异常处理程序,则此断言会报出运行期的错误 */
}



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

char
*buf = 0;
int
count = 0;


Allocation_handled = 1; /* 设置实例化异常的标志,设为1表示实例化了异常处理程序 */
if
(setjmp(Allocate_Failed)) /* 实例化异常 */
{

fprintf(stderr, "EXCEPT: Couldn't allocate the buffer\n");
exit(EXIT_FAILURE);
}


while
(1) /* 测试代码:一直分配内存,直到没有内存为止。没有内存时会触发异常 */
{

buf = (char *)allocate(4096000);
printf("Allocate successs, the count is: %d\n", count++);
}


Allocation_handled = 0;
return
0;
}


简要讲述一下代码的流程:
1.setjmp用来实例化异常处理程序,在这里我们的异常处理程序就是往stderr输出一个字符串并退出应用程序。

2.setjmp会返回2次值(颇有些fork()的味道)。setjmp第一次返回值是在应用代码(这里就是main函数里面)调用setjmp的地方,这时候它实例化了异常处理程序,并返
回0,所以异常处理程序的代码并没有被执行。在allocate中调用longjmp的时候,会引起setjmp第二次值的返回,此时的返回值由
longjmp的第二个参数所决定。文中我们调用longjmp的时候,传给它的第二个参数是1,所以setjmp返回时会执行if中的异常处理程序。


阅读(1395) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

leizisdu2015-06-03 21:21:15

博主,当longjmp的调用,触发setjmp的第2次调用时,setjmp总是返回非0值吧?

chinaunix网友2010-11-12 17:24:07

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com