自定义 SIGINT 信号处理程序 - 即使在捕获到信号后程序仍然终止

Custom SIGINT signal handler - Program still terminates even after signal is caught

我正在使用 signal.hunistd.h 库,但遇到了一些问题。在下面的代码中,当我通过调用 CTRL-CSIGINT 信号发送到我的 运行 程序时,信号被捕获。然而,当再次按下 CTRL-C 时,程序终止。据我了解,每次按 CTRL-C.

时都应打印打印语句 "Received signal 2"

是我对这个信号的理解不正确,还是我的代码有错误?

感谢您的意见!

#include "handle_signals.h"


void sig_handler(int signum)
{
    printf("\nReceived signal %d\n", signum);
}

int main()
{
    signal(SIGINT, sig_handler);
    while(1)
    {
        sleep(1);
    }
    return 0;
}

终端输出:

xxx@ubuntu:~/Dropbox/xxx/handle_signals$ ./handle_signals 
^C
Received signal 2
^C
xxx@ubuntu:~/Dropbox/xxx/handle_signals$ 

编辑:这是我包含的header

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


void sig_handler(int signum);

感谢您的回复。现在通读它们!

不要使用signal,使用sigaction:

The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.

http://man7.org/linux/man-pages/man2/signal.2.html

In the original UNIX systems, when a handler that was established using signal() was invoked by the delivery of a signal, the disposition of the signal would be reset to SIG_DFL, and the system did not block delivery of further instances of the signal.

Linux 实现相同的语义:传递信号时处理程序被重置。

signal 在接收到第一个信号时的行为因不同的实现而异。通常,它需要在收到信号后重新安装处理程序,因为处理程序已重置为其默认操作:

void sig_handler(int signum)
{  
    signal(SIGINT, sig_handler);
    printf("\nReceived signal %d\n", signum);
}

这是您不应再使用 signal 并在此处使用 sigaction. You can see a bare bone example of using sigaction 的原因之一。