8.6.Nonlocal Jumps
\(8.6.\)Nonlocal Jumps
1.Basic Concepts
- Nonlocal jumps transfers control directly from one function to another currently executing function without having to go through the normal call-and-return sequence.
Nonlocal jumps are provided by the following functions:
1 |
|
The
setjmp
function saves the current calling environment in theenv
buffer for later use bylongjmp
.- The calling environment includes the program counter, stack pointer, and general-purpose registers.
1 |
|
The
longjmp
function restores the calling environment from theenv
buffer and then triggers a return from the most recentsetjmp
call that initializedenv
.The
setjmp
then returns with the nonzero return valueretval
.- The
setjmp
function is called once but returns multiple times: once when the setjmp is first called and the calling environment is stored in the env buffer, and once for each corresponding longjmp call.
- The
An important application of nonlocal jumps is to branch out of a signal handler to a specific code location, rather than returning to the instruction that was interrupted by the signal:
1 |
|
The initial call to the
sigsetjmp
function saves the calling environment and signal context.When the user types Ctrl+C, the kernel sends a
SIGINT
signal to the process.Instead of returning from the signal handler, which would pass control back to the interrupted processing loop, the handler performs a nonlocal jump back to the beginning of the main program.
The output of the program is as below:
1 | linux> ./restart |