一、sigcation信号
二、基本用法
1.定义信号结构体
struct sigaction action
2.初始化信号结构体内容
(1)sa_flags
SA_ONSTACK:当传递信号时,信号处理程序在进程的堆栈上执行,使用了此标志位则使用不同的堆栈(DOPRA的独立信号栈)
SA_RESTART:当信号处理函数返回后,被该信号中断的系统调用将自动恢复
SA_SIGINFO:设置此参数表示使用sa_sigaction信号处理程序,默认是使用sa_handler信号处理程序
(2)sa_sigaction
// 注册信号处理函数
action.sa_sigaction = sigcapHandler
(3)sa_mask
// 清零进程屏蔽信号集
sigfillset(&action.sa_mask)
在调用sa_handler所指向的信号处理函数之前,该信号集将被加入到进程的信号屏蔽字中。信号屏蔽字是指当前被阻塞的一组信号,它们不能被当前进程接收到
3.绑定信号和对应信号处理函数
sigaction(MY_SIG, &stAction, NULL)
设置指定信号对应的新信号处理结构,并保存旧处理信号处理结构
参数2表示的是新处理结构,若参数3不为NULL,则保存旧处理结构,用于恢复
三、demo
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#define MY_SIG 11
void sigcapHandler(int a, siginfo_t *b, void *c)
{
printf("handle\n");
}
void work()
{
printf("thread is working\n");
}
void main()
{
struct sigaction stAction;
stAction.sa_flags = SA_SIGINFO | SA_ONSTACK;
stAction.sa_sigaction = sigcapHandler;
sigaction(MY_SIG, &stAction, NULL);
pthread_t id;
pthread_create(&id, 0, (void*)work, 0);
// 发送信号进入信号处理函数
pthread_kill(id, MY_SIG);
sleep(5);
}