一 点睛
signal:设置信号处理方式
表头文件
#include<signal.h>
定义函数
void (*signal(int signum,void(* handler)(int)))(int);
函数说明 signal()会依参数signum 指定的信号编号来设置该信号的处理函数。当指定的信号到达时就会跳转到参数handler指定的函数执行。
如果参数handler不是函数指针,则必须是下列两个常数之一:
- SIG_IGN :忽略参数signum指定的信号。
- SIG_DFL :将参数signum 指定的信号恢复为对信号的默认处理。
返回值
返回先前的信号处理函数指针,如果有错误则返回SIG_ERR(-1)。
二 忽略SIGNAL信号
1 代码
#include <stdio.h>
#include <signal.h>
int main(int argc, char *argv[])
{
signal(SIGINT, SIG_IGN); //忽略SIGINT信号
while (1);
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
^C^C^C^C^C^C^C^
3 说明
程序运行时,多出按下CTRL+C,但并没有使得程序退出,说明信号SIGNAL被忽略了。
三 自定义SIGNAL的处理
1 代码
#include <stdio.h>
#include <signal.h>
void signal_handler_fun(int signum) {
printf("catch signal %d\n", signum);
}
int main(int argc, char *argv[]) {
signal(SIGINT, signal_handler_fun); //注册信号处理函数的行为
while (1)
;
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
^Ccatch signal 2
^Ccatch signal 2
^Ccatch signal 2
3 可以按下CTRL+C键的时候,都会执行signal_handler_fun函数,而不退出程序。