1) setjmp()
2) longjmp()
These two routines require a datatype defined in setjmp.h:
3) jmp_buf
i) It specifies the buffer used by the routines to save and restore the program environment.
ii) The jmp_buf type is defined as: typedef char jmp_buf[_JBLEN];
iii) Example: jmp_buf env; where env- Variable in which environment is stored.
Description of 2 routines used:
1)int setjmp(env)
i)Sets up the local jmp_buf buffer and initializes it for the jump.
ii)Saves the program's calling environment in the environment buffer for later use by longjmp.
iii)If the return is from a direct invocation, setjmp returns 0.
iv)If the return is from a call to longjmp, setjmp returns a nonzero value.
2)longjmp(env,1)
i)Restores stack environment and execution locale previously saved in env by setjmp.
Generation of exception can follow the construct:
#include
jmp_buf env; <-----jump environment (must be global)
bit error_flag;
void trigger (void)
{
. . .
/* processing code here */
/* . . .
if (error_flag != 0)
{
longjmp (env, 1); <----return 1 to setjmp
}
. . .
}
Here is a simple program to generate and handle exception using setjmp() and longjmp() functions using above construct.
#include
#include
static jmp_buf buf;
void exception_handler()
{
printf("'if'detected\n"); <-----prints
longjmp(buf,1); <-----jumps back to where setjmp was called - making setjmp return 1
}
int main()
{
if (!setjmp(buf) )
{
exception_handler(); <-----when executed, setjmp returns 0
}
else
{ <-----when longjmp jumps back, setjmp returns 1
printf("Back to main block"); <-----prints
}
return 0;
}
OUTPUT is as follows:
[swati@localhost ~]$ gcc exc.c
[swati@localhost ~]$ ./a.out
'if'detected
Back to main block
No comments:
Post a Comment