longjmp() can only be used in combination with setjmp() . A call to longjmp() causesthe program to branch to a position previously saved by setjmp() . In contrast to goto jumps, which are only permitted within the same function (i.e. locally), longjmp() allows jumps from any given function to any other active function (i.e. non-local jumps).
setjmp() saves the current process environment (address in the C runtime stack, program counter, register contents) in a variable of type jmp_buf (see setjmp.h ). longjmp() restores the process environment saved by setjmp() , and the program is then continued with the statement immediately following the setjmp() call.
If no call to setjmp() precedes the longjmp() call, or if the function containing the setjmp() call has already completed execution, the results are undefined. env is the array in which setjmp() stores its values (see setjmp.h ). val is an integer that is interpreted as the return value of the setjmp call when the process returns. If val is equal to 0, setjmp() returns a value of 1; 0 would imply that control was transferred "normally" to the position after the setjmp() call, i.e. that no branch was made with longjmp() (see also setjmp() ). All accessible objects will have the same values as when longjmp() was called, except for the values of "automatic" objects (i.e. objects of automatic storage duration), which are undefined under the following conditions: They are local to the function containing the corresponding setjmp call. They are not of type volatile . They are changed between the setjmp and longjmp calls.
Since longjmp() bypasses the usual function call and return mechanisms, longjmp() will execute correctly in contexts of interrupts, signals and any of their associated functions. However, if longjmp() is invoked from a nested signal handler (that is, from a function invoked as a result of a signal raised during the handling of another signal), the behavior is undefined. After longjmp() is completed, program execution continues as if the corresponding call to setjmp() had just returned the value specified by val. The longjmp() function cannot cause setjmp() to return 0; if val is 0, setjmp() returns 1. The result of a call to this function is undefined if the jmp_buf structure was not initialized in the calling thread. The jmp_buf structure must be initialized by setjmp() . This must be done in the same thread when threads are used. |