简单地了解了一下setjmp()和longjmp(),它们的功能大抵就是实现一个跳转。
setjmp(jmp_buf) 需要一个jmp_buf的变量来储存当前数据,longjmp(jm_buf, int) 需要两个参数,一个是setjmp用的jmp_buf,另一个是int。当调用longjmp()是,程序流程跳转到对应setjmp的位置执行,并把longjmp()中参数int的值作为setjmp()的返回值,程序继续执行。
我写了一个小程序,通过这个小程序,很容易看出这两个函数是什么关系。
/*
* setjmp() and longjmp()
* mike-w
* 2012-9-30
* *************************************
* 有人用setjump()/longjump()
* 可在我这只能用setjmp()/longjmp()
* 不知道什么原因 :-(
* environment: gcc 4.5.2 on win7
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<setjmp.h>
jmp_buf buf1;
int foo(void)
{
int op;
puts("now you are in foo()");
puts("select a sentence below:");
puts("1. have a nice day");
puts("2. nice to meet you");
puts("3. it's raining cats and dogs");
while(scanf("%d", &op)!=1 || op<=0 || op>3)
fflush(stdin);
puts("jumping from foo() to main()...");
longjmp(buf1, op);
return 0;
}
int main(void)
{
puts("now you are in main()");
switch(setjmp(buf1))
{
case 0:
puts("you are still in main()");
puts("calling foo()...");
foo();
break;
case 1:
puts("have a nice day");
break;
case 2:
puts("nice to meet you.");
break;
case 3:
puts("it's raining cats and dogs");
break;
default:
puts("error!");
}
return 0;
}
执行结果:
now you are in main()
you are still in main()
calling foo()...
now you are in foo()
select a sentence below:
1. have a nice day
2. nice to meet you
3. it's raining cats and dogs
2 <- 这是我的输入
jumping from foo() to main()...
nice to meet you.