setjmp && longjmp

int setjmp ( jmp_buf env );

Save calling environment for long jump

This function with functional form takes its argument, env, and fills its content with information about the environment state in that point in the code to be able to restore that state in a later call to longjmp.

Parameters

env
Object of type jmp_buf where the environment information is stored

Return Value

This macro may return more than once. A first time, on its direct invocation, in this case it always returns zero.
When longjmp is called with the information set to env, the macro returns again; this time it returns the value passed to longjmp as second argument.

____________________________________________________________________________

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

Long jump

Restores the environment by the most recent invocation of the setjmp macro in the same invocation of the program. The information required to restore this environment is provided by parameter env, whose value is obtained from a previous call to setjmp.

The function never returns to the point where it has been invoked. Instead, the function transfers the control to the point where setjmp was used to fill the env parameter.

Parameters

env
Object of type jmp_buf containing information to restore the environment at the setjmp's calling point.
val
Value to which the setjmp expression evaluates.

Return value

None. The function never returns.

C++语言: Codee#25748
01 /* longjmp example */
02 #include <stdio.h>
03 #include <stdlib.h>
04 #include <setjmp.h>
05
06 main()
07 {
08     jmp_buf env;
09     int val;
10
11     val = setjmp(env);
12
13     printf ("val is %d\n", val);
14
15     if (!val)
16         longjmp(env, 1);
17
18     return 0;
19 }
20 /*
21 val is 0
22 val is 1
23 */
C++语言: Codee#25749
01 #include <iostream>
02 #include <csetjmp>
03 using namespace std;
04
05 class Rainbow
06 {
07 public:
08     Rainbow()
09     {
10         cout << "Rainbow()" << endl;
11     }
12     ~Rainbow()
13     {
14         cout << "~Rainbow()" << endl;
15     }
16 };
17
18 jmp_buf kansas;
19
20 void oz()
21 {
22     Rainbow rb;
23     for(int i = 0; i < 3; ++i)
24         cout << "there's no place like home" << endl;
25     longjmp(kansas, 47);
26 }
27
28 int main()
29 {
30     if(setjmp(kansas) == 0)
31     {
32         cout << "tornado,itch,munchkins..." << endl;
33         oz();
34     }
35     else
36     {
37         cout << "Auntie Em! "
38              << "I had the stranest dream..."
39              << endl;
40     }
41     cout << endl;
42
43     return 0;
44 }
45 /*
46 tornado,itch,munchkins...
47 Rainbow()
48 there's no place like home
49 there's no place like home
50 there's no place like home
51 Auntie Em! I had the stranest dream...
52
53
54 Process returned 0 (0x0)   execution time : 0.076 s
55 Press any key to continue.
56
57
58
59 */
原文地址:https://www.cnblogs.com/invisible/p/2385469.html