← 返回首页
Linux高级程序设计(四十一)
发表时间:2021-11-24 22:59:15
signal函数

signal函数是用来改变对于信号的处理方法。

函数原型:

#include <signal.h>

//将sighandler_t定义为返回值为void,接受一个int形参的函数的指针
typedef void (*sighandler_t)(int);
//现在我们可以这样书写signal函数
sighandler_t signal(int sig, sighandler_t handler);

返回值:当signal()函数成功执行时,返回值是执行signal函数之前的sig信号的处理函数的指针,如果失败,则返回SIG_ERR。

实例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
//自定义信号处理函数
void handler(int sig){
    //Ctrl+C
    if(sig==SIGINT){
        printf("自定义SIGINT正在处理中....\n");
    }
    //Ctr+Z
    if(sig==SIGSTOP){
        printf("自定义SIGSTOP正在处理中....\n");
    }
    //Ctrl+斜杠
    if(sig==SIGQUIT){
        printf("自定义SIGQUIT正在处理中....\n");
    }
}

int main(int argc, char *argv[])
{
    //以默认方式处理
#if 0
     if(signal(SIGINT,SIG_DFL)==SIG_ERR){
         perror("error to signal:");
         exit(-1);
     } 
#endif

    //以忽略的方式处理
#if 0
    if(signal(SIGINT,SIG_IGN)==SIG_ERR){
         perror("error to signal:");
         exit(-1);
    }
    //注意:SIGKILL和SIGSTOP不能忽略和自定义
    /*
    if(signal(SIGKILL,SIG_IGN)==SIG_ERR){
        perror("error to signal:");
         exit(-1);
    }*/

#endif

#if 1
    //自定义处理方式
    if(signal(SIGINT,handler)==SIG_ERR){
         perror("error to signal:");
         exit(-1);
    }

    /*注意:SIGKILL和SIGSTOP不能忽略和自定义
    if(signal(SIGSTOP,handler)==SIG_ERR){
         perror("error to signal:");
         exit(-1);
    }*/

    if(signal(SIGQUIT,handler)==SIG_ERR){
         perror("error to signal:");
         exit(-1);
    }   
#endif

    while(1){
        printf("hello,world!\n");
        sleep(1);
    }
    return 0;
}

运行结果:

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
hello,world!
hello,world!
hello,world!
hello,world!
^C自定义SIGINT正在处理中....
hello,world!
hello,world!
hello,world!
hello,world!
^\自定义SIGQUIT正在处理中....
hello,world!
hello,world!
hello,world!
^\自定义SIGQUIT正在处理中....
hello,world!
hello,world!
hello,world!
^C自定义SIGINT正在处理中....
hello,world!
hello,world!
^Z