linux c捕獲信號

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;
}

運行結果如下

[[email protected] 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]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章