蓝色天空网mbsky.com · 知识 · 实践 · 创造C++ · 本地阅读预览
教程 / 编程语言 / C++

C++ 信号处理

介绍操作系统进程信号概念、<csignal> 六个标准信号常量、std::signal 注册与返回值契约、std::raise 进程内触发机制及信号处理函数的异步安全约束。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

进程信号概念与 <csignal> 标准信号表

信号(Signal)是操作系统发送给进程的软件中断通知,常用于响应外部中断(如在类 Unix 或 Windows 终端按下 `Ctrl+C` 产生 `SIGINT`)或异常终止事件。部分底层信号不可被拦截(如 POSIX 的 `SIGKILL`),而 C++ 头文件 `<csignal>` 定义了六种跨平台可捕获的标准信号常量(详见下表)。

signal() 注册处理函数与 raise() 进程内触发

`std::signal(int sig, void (*func)(int))` 用于将指定信号与处理函数关联(也可传入 `SIG_DFL` 恢复默认行为或 `SIG_IGN` 忽略信号),并返回先前绑定的处理函数指针(失败返回 `SIG_ERR`)。示例常在循环中休眠等待 `SIGINT` 到达后执行回调并退出;需特别注意,根据 ISO C++ 标准,信号处理函数内不应直接调用 `std::cout` 或 `std::exit` 等非异步信号安全函数,工程中安全做法是仅更新 `volatile std::sig_atomic_t` 标志位,由主循环检测后执行清理退出。

`std::raise(int sig)` 可在程序内部同步向当前进程发送指定信号(成功返回 0),常用于自测信号处理逻辑或触发受控中止。例如在循环计数到达阈值后调用 `std::raise(SIGINT)`,无需人工按键即可验证已注册的信号处理回调、恢复 `SIG_DFL` 与 `SIG_IGN` 忽略语义。

<csignal> 六大标准信号常量

信号常量语义与常见触发来源
SIGABRT进程异常终止信号,如调用 std::abort() 时触发。
SIGFPE算术异常信号,如整数除以零或特定浮点异常。
SIGILL处理器检测到非法或未定义机器指令。
SIGINT交互式中断信号,常见于终端按下 Ctrl+C。
SIGSEGV非法内存访问(段错误),如解引用空指针或越界写只读页。
SIGTERM发送给进程的常规优雅终止请求信号。

使用 <csignal> 安全验证 signal()+raise() 捕获 SIGINT/SIGTERM、SIG_IGN 忽略与恢复 SIG_DFL

cpp · 阅读源码
#include <csignal>
#include <iostream>
#include <set>
#include <string>

static volatile std::sig_atomic_t g_last_signal = 0;
static volatile std::sig_atomic_t g_hit_count = 0;

extern "C" void safe_signal_handler(int signum) {
    g_last_signal = signum;
    g_hit_count = g_hit_count + 1;
}

int main() {
    // 1. Register SIGINT handler via std::signal and trigger via std::raise
    using SigHandler = void (*)(int);
    SigHandler prev_int = std::signal(SIGINT, safe_signal_handler);
    int rc_int = std::raise(SIGINT);
    int captured_int = static_cast<int>(g_last_signal);
    int count_int = static_cast<int>(g_hit_count);
    bool ok1 = (prev_int != SIG_ERR) && (rc_int == 0) &&
               (captured_int == SIGINT) && (count_int == 1);

    // 2. Register SIGTERM handler, raise, then restore SIG_DFL and verify returned handler pointer
    g_last_signal = 0;
    SigHandler prev_term_set = std::signal(SIGTERM, safe_signal_handler);
    int rc_term = std::raise(SIGTERM);
    int captured_term = static_cast<int>(g_last_signal);
    SigHandler prev_term_restore = std::signal(SIGTERM, SIG_DFL);
    bool ok2 = (prev_term_set != SIG_ERR) && (rc_term == 0) &&
               (captured_term == SIGTERM) && (prev_term_restore == safe_signal_handler);

    // 3. Ignore signal with SIG_IGN and confirm process continues cleanly
    g_last_signal = 0;
    std::signal(SIGINT, SIG_IGN);
    int rc_ign = std::raise(SIGINT);
    SigHandler prev_after_ign = std::signal(SIGINT, SIG_DFL);
    bool ok3 = (rc_ign == 0) && (g_last_signal == 0) && (prev_after_ign == SIG_IGN);

    // 4. Verify all 6 ISO C++ <csignal> constants exist and are distinct positive ints
    std::set<int> sigs = {SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM};
    bool all_pos = true;
    for (int s : sigs) {
        if (s <= 0) all_pos = false;
    }
    bool ok4 = (sigs.size() == 6) && all_pos;

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"signal_register_and_raise_sigint\", \"expected\": true, \"actual\": "
              << (ok1 ? "true" : "false") << ", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"signal_raise_sigterm_and_restore\", \"expected\": true, \"actual\": "
              << (ok2 ? "true" : "false") << ", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"signal_ignore_sig_ign\", \"expected\": true, \"actual\": "
              << (ok3 ? "true" : "false") << ", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"standard_csignal_constants\", \"expected\": true, \"actual\": "
              << (ok4 ? "true" : "false") << ", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    return 0;
}
预期结果 · 待实际运行核验
  • 在 G++ 13.3.0 C++17 离线容器中通过 volatile sig_atomic_t 回调验证 SIGINT/SIGTERM 同步捕获、signal 返回旧句柄指针、SIG_IGN 忽略后恢复 SIG_DFL 及 6 个标准信号常量 4 项全通过。
使用 <csignal> 安全验证 signal()+raise() 捕获 SIGINT/SIGTERM、SIG_IGN 忽略与恢复 SIG_DFL

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

当前源码 SHA256:9699776f064e0a5ed17728f930aeff9b6c1acace9710f9ca2e811260ca87e293

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载C++ 信号处理实验

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

ZIP SHA256:b76dfb0f2fe93be35cfe4caf7a33281fd1b03880ba53fcbc3fb0d386aee8fe01

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么工程中不建议在 `signal()` 注册的回调函数内部直接调用 `std::cout` 输出日志?安全写法是什么?

展开参考解答

信号可能在主程序正持有标准库 I/O 内部锁时异步打断执行,在回调中调用非异步信号安全函数(如 `std::cout`、`malloc`)易引发死锁或未定义行为;安全做法是在回调中仅写入 `volatile std::sig_atomic_t` 标志(或无锁原子变量),回到主线程再做日志输出与资源清理。

规范与官方依据