在SIGINT之前打印消息

时间:2018-04-01 00:55:03

标签: c signals

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

/* A signal handling function that simply prints
   a message to standard error. */
void handler(int code) {
    fprintf(stderr, "Signal %d caught\n", code);
}

int main() {
    // Declare a struct to be used by the sigaction function:
    struct sigaction newact;

    // Specify that we want the handler function to handle the
    // signal:
    newact.sa_handler = handler;

    // Use default flags:
    newact.sa_flags = 0;

    // Specify that we don't want any signals to be blocked during
    // execution of handler:
    sigemptyset(&newact.sa_mask);

    // Modify the signal table so that handler is called when
    // signal SIGINT is received:
    sigaction(SIGINT, &newact, NULL);

    // Keep the program executing long enough for users to send
    // a signal:
    int i = 0;

    for (;;) {
        if ((i++ % 50000000) == 0) {
            fprintf(stderr, ".");
        }
    }

    return 0;
}

当我按ctrl-c时,我希望我的程序打印"Signal %d caught\n"消息然后正常退出,就像按下ctrl-c时一样。

./测试 .............................. ^ CSignal 2被抓住了 ................. ^ CSignal 2被抓住了 .......................................... ^ Z [2] +停止./test

现在它只是打印信息,但不会立即退出程序。

1 个答案:

答案 0 :(得分:1)

这是因为ctrl+c的默认行为是退出程序。但是通过使用sigaction(),您自己管理行为。因此,如果您希望程序结束,则可以添加exit()来电。

void handler(int code) {
    fprintf(stderr, "Signal %d caught\n", code);
    exit(code);
}