gpt4 book ai didi

c - 信号——c99 与 gnu99

转载 作者:太空狗 更新时间:2023-10-29 15:59:31 26 4
gpt4 key购买 nike

我有以下代码。当我使用 gnu 扩展 (-std=gnu99) 编译它时,程序将在结束前捕获 5 个 SIGINT(这是我所期望的)。在没有它的情况下编译时 (-std=c99) 在第二个之后结束(并且只输出一行)。

我错过了什么?

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

int int_stage = 0;
int got_signal = 0;

void sigint(int parameter)
{
(void)parameter;
got_signal = 1;
int_stage++;
}

int main()
{
signal(SIGINT,sigint);

while(1)
{
if (got_signal)
{
got_signal = 0;
puts("still alive");
if (int_stage >= 5) exit(1);
}
}
return 0;
}

最佳答案

使用sigaction(2)而不是 signal(2) .

Linux 手册页有这个,特别是在可移植性部分:

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. System V also provides these semantics for signal(). This was bad because the signal might be delivered again before the handler had a chance to reestablish itself. Furthermore, rapid deliveries of the same signal could result in recursive invocations of the handler.

BSD improved on this situation by changing the semantics of signal handling (but, unfortunately, silently changed the semantics when establishing a handler with signal()). On BSD, when a signal handler is invoked, the signal disposition is not reset, and further instances of the signal are blocked from being delivered while the handler is executing.

The situation on Linux is as follows:

  • The kernel's signal() system call provides System V semantics.

  • By default, in glibc 2 and later, the signal() wrapper function does not invoke the kernel system call. Instead, it calls sigaction(2) using flags that supply BSD semantics. This default behav‐ ior is provided as long as the _BSD_SOURCE feature test macro is defined. By default, _BSD_SOURCE is defined; it is also implicitly defined if one defines _GNU_SOURCE, and can of course be explic‐ itly defined.
    On glibc 2 and later, if the _BSD_SOURCE feature test macro is not defined, then signal() provides System V semantics. (The default implicit definition of _BSD_SOURCE is not provided if one invokes gcc(1) in one of its standard modes (-std=xxx or -ansi) or defines various other feature test macros such as _POSIX_SOURCE, _XOPEN_SOURCE, or _SVID_SOURCE; see feature_test_macros(7).)

使用 std=gnu99,您将获得 BSD 语义。使用 -std=c99,您将获得 System V 语义。因此,在一种情况下(BSD)信号处理程序被“重新安装”,而在另一种情况下(系统 V)信号处理被重置回 SIG_DFL。

关于c - 信号——c99 与 gnu99,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288164/

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