----- Original Message -----
From: "deepa laxmi" <deeparajasekar@yahoo.com>
To: <UTTARA@yahoogroups.com>
Sent: Thursday, April 08, 2004 12:09 PM
Subject: [UTTARA] set jmp and long jmp?
> hi,
> pl can anybody tell me where setjmp and longjmp can been used and why?
>
> Deepa.R
>
The <setjmp.h> header defines the macro setjmp, and declares a function
longjmp() and a type, jmp_buf. Following are the signatures:
int setjmp(jmp_buf env);
The setjmp macro saves its calling environment in its jmp_buf argument for
later use by the longjmp function. The return value is zero if it is a direct
invocation, and non-zero if the return is from a call to longjmp().
void longjmp(jmp_buf env, int val);
The longjmp() restores the environment saved by the recent call to setjmp().
The parameter VAL is returned by setjmp().
Following program illustrates a simple usage of setjmp() and longjmp().
1
2 /*
3 * setjmp.c
4 * Author - Vijay Kumar R Zanvar <vijoeyz@hotmail.com>
5 * Date - Mar , 2004
6 */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <signal.h>
11 #include <setjmp.h>
12 #include <limits.h>
13
14 jmp_buf env;
15
16 void
17 fpe ( int sig )
18 {
19 longjmp ( env, sig );
20 }
21
22 int
23 main ( void )
24 {
25 int val = 5;
26 signal ( SIGFPE, fpe );
27 printf ( "Before: %d\n", val );
28
29 switch ( setjmp ( env ) )
30 {
31 case 0: puts ( "Return from setjmp" );
32 val = val / 0; /* SIGFPE is generated here */
33 break;
34
35 case SIGFPE: puts ( "Return from longjmp: FPE detected" );
36 /*
37 * Here we can unroll all the operation that
38 * caused floating point exception
39 */
40 printf ( "After: %d\n", val );
41 break;
42 }
43 return EXIT_SUCCESS;
44 }
45
There are few points which can be noted:
* longjmp() should not be called from an exit handler, i.e., function
registered by atexit() function.
* In an C99 implementation, the longjmp() call that returns back to
point of setjmp() invocation might cause memory associated with
variable lenght array to loose.