setjmp() Save Program State
#include <setjmp.h>
int setjmp(env);
jmp_buf env; Variable environment is stored in
setjmp() and its companion routine longjmp() provide a method of
executing a non-local goto. They would typically be used to pass
control to error-handling code in a previously called routine,
without using the normal calling conventions.
setjmp() saves the current stack environment in 'env'. A subsequent
call to longjmp() will restore the stack environment and return
control to the point just after the setjmp() call. All variables
(except register variables) accessible to the calling routine contain
the values they had when longjmp() was called.
Returns: setjmp() returns the value 0 after it saves the stack
environment. If setjmp() returns because of a subsequent
longjmp() call, it returns the 'value' argument from the
longjmp() (The 'value' argument cannot be 0). There is no
error return.
Notes: The values of register variables in the routine calling
setjmp() may be incorrectly restored after the longjmp().
-------------------------------- Example ---------------------------------
The following statements use setjmp() and longjmp() to save and
restore a stack environment.
#include <stdio.h>
#include <setjmp.h>
int val;
jmp_buf jump;
main()
{
val = setjmp(jump);
if (val != 0)
{
printf("longjmp called. control returned to setjmp. val: %d\n",
val);
exit(val);
}
printf("setjmp first called, val is %d\n",val);
s();
}
s()
{
printf("subroutine called\n");
longjmp(jump,1);
}
Seealso:
This page last updated on Fri Nov 30 10:48:32 MSK 2001
Copyright © 1992-2001, Vitaly Filatov, Moscow, Russia
Webmaster