更好地理解C中的信号捕获(即SIGINT / SIGQUIT)

时间:2014-11-05 20:23:52

标签: c terminal signals ctrl

我编写此程序来捕获 Ctrl - C 和 - \ sigintsigquit函数,我评论了我对这个程序的作用的理解。如果我错了可以纠正我,并且/或者可以解释发生了什么,这样我可以更好地理解?

//
//  main.c
//  Project 4
//
//  Found help with understanding and coding at
// http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/
//

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
//signal handling function that will except ctrl-\ and ctrl-c
void sig_handler(int signo)
{
    //looks for ctrl-c which has a value of 2
    if (signo == SIGINT)
        printf("\nreceived SIGINT\n");
    //looks for ctrl-\ which has a value of 9
    else if (signo == SIGQUIT)
        printf("\nreceived SIGQUIT\n");
}

int main(void)
{
    //these if statement catch errors
    if (signal(SIGINT, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGINT\n");
    if (signal(SIGQUIT, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGQUIT\n");
    //Runs the program infinitely so we can continue to input signals
    while(1)
        sleep(1);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

online tutorial

SIGINT可以直接使用,但您应该使用sigaction而不是signal

要捕获SIGCHLD,您可以使用教程中的代码,并使用wait()函数之一获得子状态。

void handle_sigchld(int sig) {
    int saved_errno = errno;
    while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {}
    errno = saved_errno;
}

struct sigaction sa;
sa.sa_handler = &handle_sigchld;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, 0) == -1) {
    perror(0);
    exit(1);
}