以下是signal()函數(shù)的聲明。
void (*signal(int sig, void (*func)(int)))(int)
sig -- 這是信號(hào)的處理功能被設(shè)置的號(hào)碼。以下是幾個(gè)重要的標(biāo)準(zhǔn)信號(hào)的數(shù)字:
| macro | signal |
|---|---|
| SIGABRT | (Signal Abort) Abnormal termination, such as is initiated by the function. |
| SIGFPE | (Signal Floating-Yiibai Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-yiibai operation). |
| SIGILL | (Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data. |
| SIGINT | (Signal Interrupt) Interactive attention signal. Generally generated by the application user. |
| SIGSEGV | (Signal Segmentation Violation) Invalid access to storage: When a program tries to read or write outside the memory it is allocated for it. |
| SIGTERM | (Signal Terminate) Termination request sent to program. |
func -- 這是一個(gè)指向函數(shù)的指針。這可以是由程序員或一個(gè)以下預(yù)定義的函數(shù)的定義的函數(shù):
| SIG_DFL | 默認(rèn)處理:對(duì)于某一特定信號(hào),該信號(hào)處理的默認(rèn)操作。 |
| SIG_IGN | 忽略信號(hào):信號(hào)被忽略。 |
這個(gè)函數(shù)返回前一個(gè)信號(hào)處理程序或錯(cuò)誤SIG_ERR的值。
下面的例子顯示了signal()函數(shù)的用法。
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> void sighandler(int); int main() { signal(SIGINT, sighandler); while(1) { printf("Going to sleep for a second... "); sleep(1); } return(0); } void sighandler(int signum) { printf("Caught signal %d, coming out... ", signum); exit(1); }
讓我們編譯和運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果,程序?qū)o限循環(huán)中去。跳出程序使用Ctrl + C鍵。
Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Caught signal 2, coming out...