setjmp() — Preserve Environment
Format
#include <setjmp.h>
int setjmp(jmp_buf env);
Language Level
ANSI
Threadsafe
Yes
Description
The setjmp()
function
saves a stack environment that can subsequently be restored by the longjmp()
function.
The setjmp()
and longjmp()
functions
provide a way to perform a non-local goto. They are often
used in signal handlers.
A call to the setjmp()
function
causes it to save the current stack environment in env.
A subsequent call to the longjmp()
function
restores the saved environment and returns control to a point corresponding
to the setjmp()
call.
The values of all variables (except register variables) available
to the function receiving control contain the values they had when
the longjmp()
function
was called. The values of register variables are unpredictable. Nonvolatile auto variables
that are changed between calls to the setjmp()
function
and the longjmp()
function
are also unpredictable.
Return Value
The setjmp()
function
returns the value 0 after saving the stack environment. If
the setjmp()
function
returns as a result of a longjmp()
call,
it returns the value argument of the longjmp()
function,
or 1 if the value argument of the longjmp()
function
is 0. There is no error return value.
Example
if (setjmp(mark) != 0) ...
setjmp()
function
returns a 0 when it saves the environment. The program prints the
message: setjmp has been called
The subsequent call to function p()
causes
it to call the longjmp()
function.
Control is transferred to the point in the main()
function
immediately after the call to the setjmp()
function
using the environment saved in the mark variable. This time,
the condition is TRUE because -1 is specified in the second
parameter on the longjmp()
function
call as the return value to be placed on the stack. The example then
performs the statements in the block, prints the message "longjmp()
has
been called", calls the recover()
function,
and leaves the program.
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
jmp_buf mark;
void p(void);
void recover(void);
int main(void)
{
if (setjmp(mark) != 0)
{
printf("longjmp has been called\n");
recover();
exit(1);
}
printf("setjmp has been called\n");
printf("Calling function p()\n");
p();
printf("This point should never be reached\n");
}
void p(void)
{
printf("Calling longjmp() from inside function p()\n");
longjmp(mark, -1);
printf("This point should never be reached\n");
}
void recover(void)
{
printf("Performing function recover()\n");
}
/*******************Output should be as follows: **********************
setjmp has been called
Calling function p()
Calling longjmp() from inside function p()
longjmp has been called
Performing function recover()
**********************************************************************/