signal() 函数在 signal.h 头文件中定义。它有助于处理带信号编号的信号。
void (*signal(int sig, void (*func)(int)))(int); #where sig should be in integer
signal() 函数以信号编号和函数作为其参数。一些重要的标准信号编号如下。
以下是预定义的函数
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| sig | 将处理函数设置为的信号编号。 | 必需 |
| func | 这是一个指向函数的指针。这可以是程序员定义的函数。 | 必需 |
signal() 函数返回上一个信号处理程序的值,如果出错则返回 SIG_ERR。
| 输入 | 返回值 |
|---|---|
| 如果参数 | 信号处理程序的值 |
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int main () {
signal(SIGINT, handler);
while(1) {
printf("Going to sleep for a second...\n");
sleep(1);
}
return(0);
}
void handler(int SNo) {
printf("Caught signal %d, coming out...\n", SNo);
exit(1);
}
输出
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...
#include <stdio.h>
#include <signal.h>
int main()
{
signal(SIGINT, handle_sigint);
while (1)
{
printf(“signal processing\n”);
sleep(1);
}
return 0;
}
输出
signal processing signal processing signal processing terminated