天天看點

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>

繼續閱讀