後綴jmp指的就是jump,關看名字就能猜到這哥倆是幹啥的了。使用他們倆就能夠讓程序控制流轉移,進而實現對異常的處理。html
異常處理的結構能夠劃分爲如下三個階段:linux
過程有點相似遞歸,只有文字你可能看的有點雲裏霧裏,咱們結合一個小例子來看看函數
#include <stdio.h> #include <setjmp.h> static jmp_buf buf; void second(void) { printf("second\n"); // 跳回setjmp的調用處 - 使得setjmp返回值爲1 longjmp(buf, 1); } void first(void) { second(); //這行到不了,由於second裏面longjmp已經跳轉回去了 printf("first\n"); } int main() { int rc; rc = setjmp(buf); if (rc==0) { // 進入此行前,setjmp返回0 first(); } // longjmp跳轉回,setjmp返回1,所以進入此行 else if(rc==1){ printf("main\n"); } return 0; } /* the ressult as: second main */
如今咱們再來看看兩個函數的聲明:code
固然你也能夠用switch
代替上面的if else
,其實try catch就至關於上面的那個函數你能夠參考這個實現try catch。orm
我的以爲這個在linux下更好用,而且也提供了更多的信號量宏。htm
下面給出的是signal頭文件中的定義blog
#define SIGINT 2 // interrupt #define SIGILL 4 // illegal instruction - invalid function image #define SIGFPE 8 // floating point exception #define SIGSEGV 11 // segment violation #define SIGTERM 15 // Software termination signal from kill #define SIGBREAK 21 // Ctrl-Break sequence #define SIGABRT 22 // abnormal termination triggered by abort call
這裏僅給出維基上的例子遞歸
#include <signal.h> #include <stdio.h> #include <stdlib.h> static void catch_function(int signal) { puts("Interactive attention signal caught."); } int main(void) { if (signal(SIGINT, catch_function) == SIG_ERR) { fputs("An error occurred while setting a signal handler.\n", stderr); return EXIT_FAILURE; } puts("Raising the interactive attention signal."); if (raise(SIGINT) != 0) { fputs("Error raising the signal.\n", stderr); return EXIT_FAILURE; } puts("Exiting."); return 0; }