c - GCC - 使用 POSIX 信号时优化无效

标签 c signals compiler-optimization

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

int current = 0;

void sigint_handle(int sig) {
    printf("sigint: %d\n", current);
}

int main()
{
    sigset(SIGINT, sigint_handle);

    while (1) {
        current++;
        // if (current % 1000000 == 0) printf("hey\n");
    }

    return 0;
}

使用 GCC 7.2.0 以优化级别 -O0 编译,此代码按预期工作。但是,对于任何其他优化级别,每次发送 sigint 都会打印出 sigint: 0。当输出行未注释时,无论优化如何,它也将正常工作。

我是否遗漏了一些关于信号的信息,这是 gcc 中的错误还是预期的行为(如果是,为什么?)?

最佳答案

从信号处理程序访问静态存储持续时间和类型不是 volatile sig_atomic_t 的对象会导致未定义的行为。其来源是(对于 C11):

7.14.1.1 The signal function

[...]

5 If the signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if the signal handler refers to any object with static or thread storage duration that is not a lock-free atomic object other than by assigning a value to an object declared as volatile sig_atomic_t, or...

POSIX 可能会(可能的 future 方向,尚未确定)在稍微宽松的条件下定义行为;从某种意义上说,它已经通过使用 AS 安全功能的漏洞错误地做到了。我在 Austin Group 问题跟踪器上有一个关于此主题的未解决问题:

http://austingroupbugs.net/view.php?id=728

关于c - GCC - 使用 POSIX 信号时优化无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935618/

相关文章:

c - getchld后打开文件linux eclipse c错误

matlab - 频率增加的 Simulink 正弦波

c - 对单个指针参数应用限制是否有用?

用于将 D3 js v3 迁移到 v4 的 Javascript 编译

c - 为什么一个结构不能有一个与它自己类型相同的成员?

C:用幂函数将二进制转换为十进制

c - 当你在一个用 dup2() 复制的管道文件描述符上调用 close() 时会发生什么?

c++ - C++中文字类型和变量类型之间的区别

ruby-on-rails-3 - 带有符号链接(symbolic link)的 unicorn 工作目录

c++ - C++ 编译器通常会优化静态(全局)引用吗?