/** sig.c --- demo how to catch/handle the system signal in C program ** by Wen-Nung Tsai. ** @CopyLeft reserved *** gcc sig.c *** ./a.out ****** from "man signal": SYNOPSIS #include void (*signal(int sig, void(*func)(int))() *** In signal(), it will call func in this way: (*func)(sig); **********************/ extern long time(); /* in */ #include #include #include void myisr1(int); /* an ISR to handle some interrupts */ void myisr2(int tni){printf("he he he!\n");}; /* for other signals */ long k=0, status=0, *p; jmp_buf env; /* for use in setjmp(), longjmp() */ int main() { /*** tell the system we want to catch some signals ***/ signal(SIGINT, (void (*)(int)) myisr1 ); /* See K&R Appendix B9 */ signal(SIGSEGV, *myisr1 ); /* signal(SIGSEGV, (void (*)(int)) myisr1 );*/ printf("\nWelcome to Disney Land...\n"); srand(time(0)); /* use current time to set seed of rand() */ if(rand()%100 < 50){ if(setjmp(env)==0) /* See K&R Appendix B8 */ *p=38; /* 這本來應會segmentation fault而引起 core dump ! */ else goto eoj; /* 後面的longjmp() 會跑回此處 else ! */ } printf("Here we go!\n"); loop_a_while: while(k<12345){ printf("%ld ",k++); } printf("\n=== bye bye ===\n"); return 0; eoj: system("echo -n Now:"); system("date"); printf("\n=== abnormal stop:-(\n"); return 1; } void myisr1(int x) /* Interrupt Service Routine */ { fflush(stdout); /* try to flush current buffer */ switch(x){ case SIGINT: printf("\nHey, [sig no=%d] Do NOT hit Control_C\n", x); k=12340; break; /* don't forget to take a break :-) */ default: printf("Outch! Seems Segmentation Falt or Fatal error\n"); status = 49; longjmp(env, 123); /* return a non-zero value */ } /*switch case*/ /* longjmp() will goto recent if(setjmp... */ return; }