在 C 中,我想捕获SIGINT
信号并通过使用 sigaction 并将新处理程序传递给它通过
sa.sa_sigaction = handler;
我不想终止程序。
如果我通过 shell 运行我的程序并使用 Ctrl+c 生成信号,信号处理程序将捕获信号并打印出我的消息。
之后,它将执行终止进程的默认操作。
我究竟做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
static void handler(int sig, siginfo_t* si, void *unused){
if(sig == SIGINT){
printf("Signal %i received\n",si->si_signo);
}
}
int main(int argc, char* argv[]){
char s [256];
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGINT);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
if(sigaction(SIGINT, &sa, NULL) < 0 ){
perror("sigaction");
}
fgets(s,sizeof(s), stdin);
printf("%s", s);
return 0;
}