天天看点

17、深入理解计算机系统笔记:非本地跳转

1、C提供了用户级异常控制流,称为非本地跳转(nonlocal jump),它将控制流从一个函数转移到另一个当前正在执行的函数;而不需要经过正常的调用-返回序列。通过setjmp和longjmp来实现的。

函数原形

C++提供的异常机制是高层次的,是C的setjmp,longjmp函数的更加结构化的版本。可把try语句中的catch子句看作是setjmp函数的类似物;throw语句类似于longjmp函数。

The setjmp function saves the current stack context in the env buffer, for later

use by longjmp。The longjmp function restores the stack context from the env buffer

and then triggers a return from the most recent setjmp call that initialized env. The

setjmp then returns with the nonzero return value retval.

The setjmp function is called once but returns multiple times: once when the

setjmp is first called and the stack context is stored in the env buffer, and once for

each corresponding longjmp call. On the other hand, the longjmp function is called

once but never returns。

2、应用

1)允许从一个深层嵌套的函数调用中立即返回,通常是由检测到错误引起的。

示例代码

2)使一个信号处理程序分支到一个特殊的代码位置,而不是返回到被信号到达中断了的位置。

<Computer Systems:A Programmer's Perspective>

继续阅读