1 /** sig.c --- demo how to catch/handle the system signal in C program 2 ** by Wen-Nung Tsai. ** @CopyLeft reserved 3 *** gcc sig.c 4 *** ./a.out 5 ****** from "man signal": 6 SYNOPSIS 7 #include 8 void (*signal(int sig, void(*func)(int))() 9 *** In signal(), it will call func in this way: 10 (*func)(sig); 11 **********************/ 12 extern long time(); /* in */ 13 #include 14 #include 15 #include 16 void myisr1(int); /* an ISR to handle some interrupts */ 17 void myisr2(int tni){printf("he he he!\n");}; /* for other signals */ 18 long k=0, status=0, *p; 19 jmp_buf env; /* for use in setjmp(), longjmp() */ 20 int main() 21 { /*** tell the system we want to catch some signals ***/ 22 signal(SIGINT, (void (*)(int)) myisr1 ); /* See K&R Appendix B9 */ 23 signal(SIGSEGV, *myisr1 ); /* signal(SIGSEGV, (void (*)(int)) myisr1 );*/ 24 printf("\nWelcome to Disney Land...\n"); 25 srand(time(0)); /* use current time to set seed of rand() */ 26 if(rand()%100 < 50){ 27 if(setjmp(env)==0) /* See K&R Appendix B8 */ 28 *p=38; /* 這本來應會segmentation fault而引起 core dump ! */ 29 else goto eoj; /* 後面的longjmp() 會跑回此處 else ! */ 30 } 31 printf("Here we go!\n"); 32 loop_a_while: 33 while(k<12345){ 34 printf("%ld ",k++); 35 } 36 printf("\n=== bye bye ===\n"); return 0; 37 eoj: 38 system("echo -n Now:"); system("date"); 39 printf("\n=== abnormal stop:-(\n"); return 1; 40 } 41 void myisr1(int x) /* Interrupt Service Routine */ 42 { 43 fflush(stdout); /* try to flush current buffer */ 44 switch(x){ 45 case SIGINT: 46 printf("\nHey, [sig no=%d] Do NOT hit Control_C\n", x); 47 k=12340; 48 break; /* don't forget to take a break :-) */ 49 default: 50 printf("Outch! Seems Segmentation Falt or Fatal error\n"); 51 status = 49; 52 longjmp(env, 123); /* return a non-zero value */ 53 } /*switch case*/ /* longjmp() will goto recent if(setjmp... */ 54 return; 55 } /*** 說明執行這程式會怎樣以及結束前敲Control_C會如何? (hint: 多試幾次! 用到的函數都可在 K&R 的附錄B 中找到, 中英文皆同) (以後如果你的工作是寫程式, 這程式對你非常有用! 信不信由你:-) ******/ From: jwlin@csie.nctu.edu.tw (蔚藍~~~~) 試了幾次..........有兩種情況.............. 第一種就是一直印數字,在印到 12344時會結束.....印出掰掰..... 假如按 ctrl-c 會出現Hey, [sig no=2] Do NOT hit Control_C 然後又印一些, 但一定印到 12344 程式結束,印出掰掰......... 第二種就是直接Segmentation Falt or Fatal error 印出=== abnormal stop:-( 就結束了........ 1 2 ... 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7^C Hey, [sig no=2] Do NOT hit Control_C 7915 7916 7917 7918 12340 12341 12342 12343 12344 === bye bye === Welcome to Disney Land... Outch! Seems Segmentation Falt or Fatal error Now:Wed May 15 20:44:42 CST 1996 === abnormal stop:-(