Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在SIGINT之前打印消息_C_Signals - Fatal编程技术网

C 在SIGINT之前打印消息

C 在SIGINT之前打印消息,c,signals,C,Signals,当我按ctrl-c时,我希望我的程序打印信号%d捕获的消息,\n然后像按ctrl-c时一样正常退出 /测试 信号2被捕获 信号2被捕获 ………^Z [2] +停止/测试 现在它只打印消息,但不会立即退出程序。这是因为ctrl+c的默认行为是退出程序。但是通过使用sigaction,您可以自己管理行为。因此,如果希望程序结束,可以添加退出调用 尽管Ctrl-C不应作为1退出。Ctrl-C是SIGINT,所以我返回SIGINT;有关所有值,请参阅signal.h。读取。fprintf和exit都不是

当我按ctrl-c时,我希望我的程序打印信号%d捕获的消息,\n然后像按ctrl-c时一样正常退出

/测试 信号2被捕获 信号2被捕获 ………^Z [2] +停止/测试


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

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


尽管Ctrl-C不应作为1退出。Ctrl-C是SIGINT,所以我返回SIGINT;有关所有值,请参阅signal.h。读取。fprintf和exit都不是异步信号安全的,所以原则上,您不应该从信号句柄调用它们。如果在Linux上,则读并。由于fprintf不是异步信号安全函数,因此原则上不允许从信号处理程序调用它。
#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;
}
void handler(int code) {
    fprintf(stderr, "Signal %d caught\n", code);
    exit(code);
}