signal()函数的使用

一、函数介绍

头文件:

#include <signal.h>

原型:

typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler);

描述:

signal() sets the disposition of the signal signum to handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined function (a "signal handler").
If the signal signum is delivered to the process, then one of the following happens:
*  If the disposition is set to SIG_IGN, then the signal is ignored.
*  If the disposition is set to SIG_DFL, then the default action associated with the signal (see signal(7)) occurs.
*  If the disposition is set to a function, then first either the disposition is reset to SIG_DFL, or the signal is blocked (see Portability below), and then handler  is
   called with argument signum.  If invocation of the handler caused the signal to be blocked, then the signal is unblocked upon return from the handler.
The signals SIGKILL and SIGSTOP cannot be caught or ignored.

返回值:

signal() returns the previous value of the signal handler, or SIG_ERR on error.  In the event of an error, errno is set to indicate the cause.

二、使用方法

编写 signal 函数 测试代码,此程序使用了 exit 函数 退出程序,如下:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>


void close_sighandler(int signum)
{
        
        printf("\n rx signum =  %d\n",signum);
        printf("exit.......\n");
        exit(1);//退出
}


int main(void)
{
   signal(SIGINT, close_sighandler);


   while(1) 
   {
      printf("main fun...\n");
      sleep(1);
   }


   return(0);
}

实验结果:

d66438c1decefcf590b677a9df815d40.png

官方推荐使用 sigaction函数代替signal函数,sigaction函数的使用可参考如下:

https://blog.csdn.net/weibo1230123/article/details/81411827

欢迎关注公众号:嵌入式学习与实践

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值