gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:45:44 24 4
gpt4 key购买 nike

我正在使用 signal.hunistd.h 库,但遇到了一些问题。在下面的代码中,当我通过调用 CTRL-C 向正在运行的程序发送 SIGINT 信号时,该信号被捕获。然而,当再次按下 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$

编辑:这是我包含的标题

#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 实现了相同的语义:当信号被传递时处理程序被重置。

关于自定义 SIGINT 信号处理程序 - 即使在捕获到信号后程序仍然终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31285336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com