linux c捕获信号

来源:互联网 发布:数据透视表显示合计 编辑:程序博客网 时间:2024/05/16 14:07

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) {    // get pid of sender,    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() {    // print pid    printf("process [%d] started.\n", (int)getpid());    // prepare sigaction    siga.sa_sigaction = *multi_handler;    siga.sa_flags |= SA_SIGINFO; // get detail info    // change signal action,    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;    }    // use "ctrl + c" to send SIGINT, and "ctrl + \" to send SIGQUIT,    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); // send signal to itself    sleep(1); // sleep a while, note that: SIGINT will interrupt this, and make program wake up,    }    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]
0 0
原创粉丝点击