sigaction函数的功能是检查或(/并)修改与指定信号相关联的处理动作.建议使用sigaction, 而不是signal函数, 后者较老,不可靠.
#include <signal.h>
int sigaction( int signo, const struct sigaction *restrict act, struct sigaction *restrict oact);
返回值:若成功则返回0,若出错则返回-1
act指针非空, 则修改信号的动作;
oact指针非空, 则返回该信号的上一个动作.
结构体介绍:
struct sigaction {
void (*sa_handler)(int); /* addr of signal handler, or SIG_IGN, or SIG_DFL */
sigset_t sa_mask; /* additional signals to block */
int sa_flags; /* signal options */
/* alternate handler */
void (*sa_sigaction)(int, siginfo_t *, void *);
};
代码实例:
static int g_quit;
static void handle_signal(int sig)
{
if (SIGINT == sig || SIGTERM == sig)
g_quit = 1;
}
static struct sigaction sigact = {
.sa_handler = handle_signal,
};
int main(void) {
int ret = 0;
ret = sigaction(SIGINT, &sigact, NULL);
ret |= sigaction(SIGTERM, &sigact, NULL);
if (ret) {
printf("%s line%d: %s\n",
__FILE__, __LINE__, strerror(errno));
return -1;
}
do {
if (g_quit == 1)
break;
} while(1);
return 0;
}
参考: 信号之sigaction函数 http://www.cnblogs.com/nufangrensheng/p/3515945.html