setjmp和longjmp函数组合使用,用来保证程序局部跳转的指令.与goto语句不同之处在于它保存程序堆栈,使程序可以完成比goto更多的功能.通常用来实现程序控制流的转移并对程序中的异常进行集中处理.
让我们来看看MSDN中是怎么说的
The setjmp function saves a stack environment, which you can subsequently restore using longjmp. When used together, setjmp and longjmp provide a way to execute a “non-local goto.” They are typically used to pass execution control to error-handling or recovery code in a previously called routine without using the normal calling or return conventions.
A call to setjmp saves the current stack environment in env. A subsequent call to longjmp restores the saved environment and returns control to the point just after the corresponding setjmp call. All variables (except register variables) accessible to the routine receiving control contain the values they had when longjmp was called.
setjmp and longjmp do not support C++ object semantics. In C++ programs, use the C++ exception-handling mechanism.
最重要的是它可以保存当前stack,并用longjmp恢复.要理解它我们首先要看看stack在程序中的作用.
stack是用来保存程序中的局部变量和函数参数.我们调用一个函数通常产生的汇编代码如下:
push param3
push param2
push param1
call function
ret
CPU寄存器使用SS ESP来保存栈底及栈顶指针.而我们要保证程序可以随意的在程序之间跳转除了要保证FLAG CS:IP在程序中的改变外,堆栈也是一个必要的因素,否则程序会产生0x0000000fdh异常,而setjmp正好为我们完成了这样的功能.使我们有了不使用汇编语言即可完成底层语言的实现功能.
关于使用的代码大家可以去google上查一下.很多很多.这是我第一次写文章,自己也感觉写的不怎么好.嘿嘿