setjmp
Sets up for nonlocal goto.
Defined in header <setjmp.h>
Syntax
#include <setjmp.h>
int setjmp (jmp_bufym/?&);
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ | ■ |
Remarks
setjmp captures the complete task state in jmpb and returns 0.
A later call to longjmp with jmpb restores the captured task state and returns in such a way that setjmp appears to have returned with the value val.
A task state is
■ all segment registers (CS, DS, ES, SS)
B register variables (SI, DI) ■ stack pointer (SP) ■ frame base pointer (BP) ■ flags
A task state is complete enough that setjmp can be used to implement coroutines.
setjmp must be called before longjmp. The routine that calls setjmp and sets up jmpb must still be active and cannot have returned before the longjmp is called. If it has returned, the results are unpredictable.
setjmp is useful for dealing with errors and exceptions encountered in a low-level subroutine of a program.
^i^
You can't use setjmp and longjmp for implementing co-routines if your program is overlaid. Normally, setjmp and longjmp save and restore all the registers needed for co-routines, but the overlay manager needs to keep track of stack contents and assumes there is only one stack. When you implement co-routines there are usually either two stacks or two partitions of one stack, and the overlay manager will not track them properly.
You can have background tasks which run with their own stacks or sections of stack, but you must ensure that the background tasks do not invoke any overlaid code, and you must not use the overlay versions of setjmp or longjmp to switch to and from background. When you avoid using overlay code or support routines, the existence of the background stacks does not disturb the overlay manager.
Return value
setjmp returns 0 when it is initially called. If the return is from a call to longjmp, setjmp returns a nonzero value (as in the example).
See also
Example
#include <stdio.h>
#include <process.h>
#include <setjmp.h>
void subroutine (void);
jmp_buf jumper;
int main( )
(
int value;
value = setjmp (jumper);
if (value != 0) {
printf ("Longjmp with value %d\n", value)
exit (value);
}
printf ("About to call subroutine ... \n");
subroutine 0 ;
return 0;
}
void subroutine (void) {
longjmp (jumper,1);
}
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Stable link: /3.1/setjmp.h/setjmp/
· short form /3.1/setjmp/