一、函数介绍
头文件:
#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);
}
实验结果:
官方推荐使用 sigaction函数代替signal函数,sigaction函数的使用可参考如下:
https://blog.csdn.net/weibo1230123/article/details/81411827
欢迎关注公众号:嵌入式学习与实践