signal() - C函数
声明
以下是signal()函数的声明。
void (*signal(int sig, void (*func)(int)))(int)
参数
-
sig -- 这是信号的处理功能被设置的号码。以下是几个重要的标准信号的数字:
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 -- 这是一个指向函数的指针。这可以是由程序员或一个以下预定义的函数的定义的函数:
SIG_DFL | 默认处理:对于某一特定信号,该信号处理的默认操作。 |
SIG_IGN | 忽略信号:信号被忽略。 |
返回值
这个函数返回前一个信号处理程序或错误SIG_ERR的值。
例子
下面的例子显示了signal()函数的用法。
#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); }
让我们编译和运行上面的程序,这将产生以下结果,程序将无限循环中去。跳出程序使用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...