1

在 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;
}
4

1 回答 1

2

问题是fgets会调用read系统调用,而系统调用会在被 中断时返回错误SIGINT,请参见阅读手册页:

EINTR 在读取任何数据之前调用被信号中断;见信号(7)。

So you should check the errno of fgets and if it was EINTR continue to call fgets. Try my updated program:

#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>
#include <errno.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 = {0};

    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");
    }

    char *p;
    do {
        p = fgets(s,sizeof(s), stdin);
    } while (!p && errno == EINTR);
    printf("%s\n", s);
    return 0;
}
于 2017-03-17T09:30:45.893 回答