imtinge

在C程序里面乱跳

在代码里面看到jmp_buf不认识,wiki了一下http://zh.wikipedia.org/zh/Setjmp.h

里面看到一个示例程序,看完觉得这个跳得很欢喜

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <setjmp.h>
 5  
 6 void first(void);
 7 void second(void);
 8  
 9 /* This program's output is:
10  
11 calling first
12 calling second
13 entering second
14 second failed with type 3 exception; remapping to type 1.
15 first failed, exception type 1
16  
17 */
18  
19 /* Use a file scoped static variable for the exception stack so we can access
20  * it anywhere within this translation unit. */
21 static jmp_buf exception_env;
22 static int exception_type;
23  
24 int main() {
25     void *volatile mem_buffer;
26  
27     mem_buffer = NULL;
28     if (setjmp(exception_env)) {
29         /* if we get here there was an exception */
30         printf("first failed, exception type %d\n", exception_type);
31     } else {
32         /* Run code that may signal failure via longjmp. */
33         printf("calling first\n");
34         first();
35         mem_buffer = malloc(300); /* allocate a resource */
36         printf(strcpy((char*) mem_buffer, "first succeeded!")); /* ... this will not happen */
37     }
38     if (mem_buffer)
39         free((void*) mem_buffer); /* carefully deallocate resource */
40     return 0;
41 }
42  
43 void first(void) {
44     jmp_buf my_env;
45  
46     printf("calling second\n");
47     memcpy(my_env, exception_env, sizeof(jmp_buf));
48     switch (setjmp(exception_env)) {
49         case 3:
50             /* if we get here there was an exception. */
51             printf("second failed with type 3 exception; remapping to type 1.\n");
52             exception_type = 1;
53  
54         default: /* fall through */
55             memcpy(exception_env, my_env, sizeof(jmp_buf)); /* restore exception stack */
56             longjmp(exception_env, exception_type); /* continue handling the exception */
57  
58         case 0:
59             /* normal, desired operation */
60             second();
61             printf("second succeeded\n");  /* not reached */
62     }
63     memcpy(exception_env, my_env, sizeof(jmp_buf)); /* restore exception stack */
64 }
65  
66 void second(void) {
67     printf("entering second\n" ); /* reached */
68     exception_type = 3;
69     longjmp(exception_env, exception_type); /* declare that the program has failed */
70     printf("leaving second\n"); /* not reached */
71 }

 

posted on 2012-11-07 14:17  imtinge  阅读(159)  评论(0)    收藏  举报