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

标签 c terminal signals ctrl

我写这个程序是为了捕获 Ctrl-C 和 -\ 或者 sigint sigquit 函数,我评论了我对这个程序的作用的理解。如果我错了,您能否纠正我和/或解释一下发生了什么,以便我能更好地理解?

//
//  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;
}

最佳答案

有一个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);
}

关于c - 更好地理解 C 中的信号捕获(即 SIGINT/SIGQUIT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26766419/

相关文章:

C -> Shell - 阻止写入直到读取

c - 有没有一种方法可以使用链表来简化我的蒙特卡洛代码

multithreading - 如何在不使用join的情况下向python中的主线程发送信号?

linux - Bash 脚本在设定的时间后自动终止进程,还处理用户中断

c - 视频内存访问和后缀递增

java - 通过java运行终端命令

mysql - 通过终端将数据库导入 MAMP,无法连接

linux - 如何使用 linux 命令行工具列出文本文件中使用的唯一字符?

python - 了解 scipy 反卷积

C - stdin 到变量