NAME signal - ANSI C signal handlingSYNOPSIS #include <signal.h> typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler);
signal函數具有注冊功能,什么事都不干。只是告訴系統,當來信號signum時,按handler的方式處理。只有來信號時,才會調用這個函數。信號不來,永遠不會調用這個函數。
用戶能夠通過輸入CTRL+c、Ctrl+/,或者是終端驅動程序分配給信號控制字符的其他任何鍵來請求內核產生信號。
ctrl + c --> 2)SIGINT ctrl + / --> 3)SIGQUIT
以上兩者都可以讓程序退出。
代碼/************************************************************************* > File Name: hello.c > Author: KrisChou > Mail:zhoujx0219@126.com > Created Time: Mon 25 Aug 2014 09:25:15 AM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/stat.h>#include <sys/types.h>#include <fcntl.h>#include <assert.h>#include <signal.h>#include <sys/select.h>void handler(int num){ PRintf("sig_num: %d /n", num);}int main(int argc, char* argv[]){ char buf[1024]; signal(2, handler); int iret ; fd_set read_set, ready_set ; FD_ZERO(&read_set); FD_SET(0, &read_set); while(1) { ready_set = read_set ; iret = select(1, &ready_set, NULL, NULL, NULL); if(iret == 0) { continue ; }else if(iret == -1) { perror("select"); continue ; }else { iret = read(0, buf, 1024); buf[iret] = '/0'; write(1, buf, strlen(buf)); } }程序運行后先按ctrl+c,結果如下:
[purple@localhost review]$ gcc test.c[purple@localhost review]$ ./a.out^Csig_num: 2select: Interrupted system callhello world!hello world!
由于SIGINT已經通過signal(2, handler);進行注冊了, 因此很顯然當按下ctrl+c后,信號處理函數handler自然會捕捉到這個信號,因此會顯示^Csig_num: 2 。
而select函數 會處理中斷信號。收到中斷信號,會返回-1。 因此顯示select: Interrupted system call select 。
注意:select函數在3中情況下會返回,分別是:輪詢時間到點會返回。收到信號會返回。描述符有活動會返回。
(順帶補充下:read 是 阻塞函數,收到信號時先處理信號, 接著繼續等。)
之后程序運行就很顯然了。有輸入,select返回1,輸入什么,就打印什么。按ctrl+d,select返回0,程序繼續運行。
新聞熱點
疑難解答