linux c捕获信号
在程序中为了实现优雅退出,需要对信号进行处理,本文主要记录一下两个方面:
* 如何捕获SIGINT、SIGTERM、SIGQUIT等信号,并进行处理
* 如何知道是哪个进程给自己发送的信号
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
static int int_count = 0;
static int max_int = 5;
static int max_term = 10;
static struct sigaction siga;
static void multi_handler(int sig, siginfo_t *siginfo, void *context) {
pid_t sender_pid = siginfo->si_pid;
if(sig == SIGINT) {
printf("INT(%d), from [%d]\n", int_count++, (int)sender_pid);
} else if(sig == SIGQUIT) {
printf("Quit, bye, from [%d]\n", (int)sender_pid);
exit(0);
} else if(sig == SIGTERM) {
printf("TERM(%d), from [%d]\n", int_count++, (int)sender_pid);
}
return;
}
int raise_test() {
printf("process [%d] started.\n", (int)getpid());
siga.sa_sigaction = *multi_handler;
siga.sa_flags |= SA_SIGINFO;
if (sigaction(SIGINT, &siga, NULL) != 0) {
printf("error sigaction()");
return errno;
}
if (sigaction(SIGQUIT, &siga, NULL) != 0) {
printf("error sigaction()");
return errno;
}
if (sigaction(SIGTERM, &siga, NULL) != 0) {
printf("error sigaction()");
return errno;
}
int sig;
while (1) {
if (int_count < max_int) {
sig = SIGINT;
} else if (int_count >= max_int && int_count < max_term) {
sig = SIGTERM;
} else {
sig = SIGQUIT;
}
raise(sig);
sleep(1);
}
return 0;
}
int main(int argc, char *argv[]) {
raise_test();
return 0;
}
运行结果如下
[root@hz01-noah-yanzhijie1.hz01.baidu.com check]# ./noah-agent
process [64619] started.
INT(0), from [64619]
INT(1), from [64619]
INT(2), from [64619]
INT(3), from [64619]
INT(4), from [64619]
TERM(5), from [64619]
TERM(6), from [64619]
TERM(7), from [64619]
TERM(8), from [64619]
TERM(9), from [64619]
Quit, bye, from [64619]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)