Linux环境编程之进程(三):函数间跳转

引言:在编写程序时,经常在函数内部使用goto语句来跳转,从而进行出错处理,那么如果想要在函数之间进行跳转该怎么做呢?使用setjmp和longjmp函数。

给出示例程序:

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

static void f1(int, int, int, int);
static void f2(void);

static jmp_buf 	jmpbuffer;
static int 		globval;

int
main(void)
{
	int 	autoval;
	register int regival;
	volatile int volaval;
	static 	int  statval;

	globval = 1;
	autoval = 2;
	regival = 3; 
	volaval = 4;
	statval = 5;

	if(setjmp(jmpbuffer) != 0){
		printf("after longjmp:\n");
		printf("global = %d, autoval = %d, regival  = %d, volaval = %d, statval = %d\n", 
						globval, autoval, regival, volaval, statval);
		exit(0);	
	}
	/*
	 * Change variable after setjmp, buf before longjmp.
	 */
	globval = 95;
	autoval = 96;
	regival = 97; 
	volaval = 98;
	statval = 99;

	f1(autoval, regival, volaval, statval);/*never returns*/
	exit(0);
}

static void
f1(int i, int j, int k, int l)
{
	printf("in f1():\n");
	printf("global = %d, autoval = %d, regival  = %d, volaval = %d, statval = %d\n", 
						globval,i, j, k, l);
	f2();
}
static void
f2(void)
{
	longjmp(jmpbuffer, 1);
}

编译程序测试结果:

in f1():
global = 95, autoval = 96, regival  = 97, volaval = 98, statval = 99
after longjmp:
global = 95, autoval = 96, regival  = 97, volaval = 98, statval = 99


Linux环境编程之进程(三):函数间跳转,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。