第一个参数是内核中的信号量编号,第二个是用户自定义函数。
Linux中的常见信号量如下:
其中SIGINT就是用户输入ctr+C时对应的信号量,可以将ctr+C信号替换成自定义函数:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void fun_sig(int sig){
printf("sig=%d\n",sig);
//signal(SIGINT,SIG_DFL); //默认
}
int main(){
//signal(SIGINT,SIG_DFL); //默认
//signal(SIGINT,SIG_IGN); //ignore ;忽略ctr+c信号
signal(SIGINT,fun_sig);//与内核约定,收到ctr+c信号时不退出,改为调用fun_sig();
while(1){
printf("hello\n");
sleep(1);
}
exit(1);
}
由于与内核约定了遇到SIGINT类型的信号改为用户自定义函数的处理,所以无法用ctr+C进行终端中断。