Page

2015년 10월 2일 금요일

setjump, longjump

int setjmp(jmp_buf env);
void longjmp(jmp_buf env, int val);

When setjmp is just called, it saves the values of current registers to jmp_buf variable and returns 0.

When longjmp is called with the same jmp_buf, the values of current registers are set as the saved values so that it goes back to the returning point of setjmp.
At the same time, setjmp returns the second argument passed to  longjmp.


 #include <stdio.h>
#include <setjmp.h>

#define TRY do{ jmp_buf ex_buf__; switch( setjmp(ex_buf__) ){ case 0:
#define CATCH(x) break; case x:
#define ETRY } }while(0)
#define THROW(x) longjmp(ex_buf__, x)

#define FOO_EXCEPTION (1)
#define BAR_EXCEPTION (2)
#define BAZ_EXCEPTION (3)

int main(int argc, char** argv)
{
   TRY
   {
      printf("In Try Statement\n");
      THROW( BAR_EXCEPTION );
      printf("I do not appear\n");
   }
   CATCH( FOO_EXCEPTION )
   {
      printf("Got Foo!\n");
   }
   CATCH( BAR_EXCEPTION )
   {
      printf("Got Bar!\n");
   }
   CATCH( BAZ_EXCEPTION )
   {
      printf("Got Baz!\n");
   }
   ETRY;

   return 0;
}

ref: http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html