Example (longjmp -- Restore Stack Environment)

This example saves the stack environment at the statement:

if(setjmp(mark) != 0) ...

When the system first performs the if statement, it saves the environment in mark and sets the condition to FALSE because setjmp returns a 0 when it saves the environment. The program prints the message:

setjmp has been called

The subsequent call to function p tests for a local error condition, which can cause it to call longjmp. Then, control returns to the original setjmp function using the environment saved in mark. This time, the condition is TRUE because -1 is the return value from longjmp. The example then performs the statements in the block, prints "longjmp has been called", calls recover, and leaves the program.

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
int p(void);
int recover(void);
jmp_buf mark;
int main(void)
{
   if (setjmp(mark) != 0) {
      printf("longjmp has been called\n");
      recover();
      exit(1);
   }
   printf("setjmp has been called\n");
   p();
   return 0;
   /*********************************************
      The output should be:
      setjmp has been called
      longjmp has been called
   *********************************************/
}
int p(void)
{
   int error = 0;
   error = 9;
   if (error != 0)
      longjmp(mark, -1);
   return 0;
}
int recover(void)
{
   return 0;
}