qfedu-linux-advanced-level/day3/test_sigaction.c

39 lines
756 B
C
Raw Permalink Normal View History

2023-08-17 09:20:18 +08:00
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void sigint_handler(int signum)
{
printf("捕捉到 SIGINT 信号,程序即将退出。\n");
exit(0);
}
int main()
{
struct sigaction sa;
sa.sa_handler = sigint_handler;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGINT);
sigfillset(&sa.sa_mask);
// sa.sa_flags = 0;
sa.sa_flags |= SA_RESETHAND; // 重置默认的信号处理行为
if (sigaction(SIGINT, &sa, NULL) == -1)
{
perror("sigaction");
exit(1);
}
printf("程序运行中,按 Ctrl+C 发送 SIGINT 信号退出。\n");
while (1)
{
// 程序持续执行
sleep(1);
}
return 0;
}