#include <stdio.h>
#include <signal.h>
#include <stdbool.h>
static volatile sig_atomic_t g_last_sig = 0;
static volatile sig_atomic_t g_count = 0;
static void safe_handler(int sig) {
g_last_sig = sig;
g_count = g_count + 1;
}
int main(void) {
void (*prev1)(int) = signal(SIGTERM, safe_handler);
int r1 = raise(SIGTERM);
bool c1_pass = (prev1 != SIG_ERR && r1 == 0 && g_last_sig == SIGTERM && g_count == 1);
void (*prev2)(int) = signal(SIGTERM, SIG_IGN);
int r2 = raise(SIGTERM);
bool c2_pass = (prev2 != SIG_ERR && r2 == 0 && g_count == 1);
void (*prev3)(int) = signal(SIGTERM, SIG_DFL);
int macros_ok = (SIG_DFL != SIG_IGN && SIG_ERR != SIG_DFL && SIG_ERR != SIG_IGN && sizeof(sig_atomic_t) >= 1) ? 1 : 0;
bool c3_pass = (prev3 == SIG_IGN && macros_ok == 1);
printf(
"{"
"\"runtime\":\"GCC C11 (mstorsjo/llvm-mingw:20260616)\","
"\"cases\":["
"{\"name\":\"signal_handler_and_raise\",\"expected\":\"r=0,match=1,count=1\",\"actual\":\"r=%d,match=%d,count=%d\",\"passed\":%s},"
"{\"name\":\"sig_ign_ignores_signal\",\"expected\":\"r=0,count=1\",\"actual\":\"r=%d,count=%d\",\"passed\":%s},"
"{\"name\":\"sig_dfl_restore_and_macros\",\"expected\":\"prev_ign=1,macros=1\",\"actual\":\"prev_ign=%d,macros=%d\",\"passed\":%s}"
"]"
"}\n",
r1, (g_last_sig == SIGTERM) ? 1 : 0, (int)g_count, c1_pass ? "true" : "false",
r2, (int)g_count, c2_pass ? "true" : "false",
(prev3 == SIG_IGN) ? 1 : 0, macros_ok, c3_pass ? "true" : "false"
);
return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。
入口文件:projects/c-standard-library-signal-h-lab/explore-standard-library-signal-h.c
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-standard-library-signal-h.c,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3251.zip
课程关联工程包(登记关联63章) · 含当前章节或实例 · mbskycom202612a3210.zip