linux下如何实现全局跳转

C语言中的goto语句只能实现函数中的局部跳转,并不能实现全局跳转

查阅LinuxC 以后,简介如何实现及运用全局跳转(不同函数中的跳转)

Linux 下的全局跳转的实现及其原理:
所用的函数及其头文件:

setjmp();
longjmp()

在linux下的例子程序:
         #include                                                                                 
       2 #include
       3 jmp_buf env;//储存栈帧
       4 void f(void)
-      5 {   
|      6     longjmp(env,10);//恢复env所保存的栈帧,longjmp参数的值作为setjmp的返回值
|      7     printf("this is after the function longjmp");//不执行该程序
|      8 }
       9 
      10 int main()
-     11 {
|     12     int val;
|     13     printf("this is before the function setjmp()\n");
|     14     val=setjmp(env);//进入setjmp函数,第一次进入功能是把当前函数栈帧保存在env中,当longjmp()返回
|        时仍在setjmp内部,返回longjmp中参数的值
|     15     if(val!=0)//第一次进入,即还没有跳转
|-    16     {
||    17         printf("after long jump,the value is %d\n",val);
||    18     }else//跳转后的
|-    19     {
||    20         printf("read to jump\n");
||    21         f();
||    22     }
|     23     val=setjmp(env);
|     24     printf("val=%d\n",val);
|     25     return 0;
|     26 }  
运行结果:


this is before the function setjmp()
read to jump
after long jump,the value is 10
val=0


原理:
setjmp(env)函数把其所在的函数的栈帧保存在其jmp_buf类型的参数env中;
longjmp(env,10)   longjmp 函数把env储存的栈帧恢复,并跳转到setjmp函数中,setjmp函数返回参数值10。


使用方法:
#include
#include
#include
jmp_buf  env;
void f(void)
{
	longjmp(env,1);
} 

int main()
{
	if()   setjmp(env);
	
	return 0;
}

注意:再次使用setjmp()第一次储存栈帧返回值为0


你可能感兴趣的:(操作系统)