sigaction函数是用作检查/修改与指定信号相关联的处理动作. 在UNIX早期版本中使用signal, 后来改用了sigaction, 可见它的功能比signal要强大. 另外, signal函数也是可以用sigaction实现的.
1. sigaction原型:
#include <signal.h>
int sigaction(int signo, const struct sigaction *restrict act,
int sigaction(int signo, const struct sigaction *restrict act,
struct sigaction *
restrict oact);
成功则返回0, 出错则返回-1.
成功则返回0, 出错则返回-1.
首先说一下struct sigaction这个结构:
struct
sigaction
{
void (*sa_handler)(int); /* addr of signal handler or
{
void (*sa_handler)(int); /* addr of signal handler or
SIG_IGN, SIG_DFL */
sigset_t sa_mask; /* additional signals to block */
int sa_flags; /* signal options */
/* alternate handler */
void (*sa_sigaction)(int, siginfo_t *, void * );
};
sigset_t sa_mask; /* additional signals to block */
int sa_flags; /* signal options */
/* alternate handler */
void (*sa_sigaction)(int, siginfo_t *, void * );
};
- sa_hanlder: 一个带有int参数的函数指针, 或者SIG_IGN(忽略), 或者SIG_DFL(默认).
- sa_mask: 信号屏蔽字(集). 当该信号处理函数返回时, 屏蔽字恢复.
- sa_sigaction: 替代的信号处理程序, 当使用了SA_SIGINFO标志时, 使用该信号处理程序.
对于sa_flags和siginfo结构, 具体参考APUE 262页.
2. 实例:
用sigaction实现signal:
typedef void (*sig_func)(int
);
sig_func *signal(int signo, sig_func * func);
{
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(& act.sa_mask);
act.sa_flags = 0 ;
if (sigaction(signo, &act, &oact) < 0 )
return SIG_ERR;
return oact.sa_hanlder;
}
sig_func *signal(int signo, sig_func * func);
{
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(& act.sa_mask);
act.sa_flags = 0 ;
if (sigaction(signo, &act, &oact) < 0 )
return SIG_ERR;
return oact.sa_hanlder;
}