C语言 在 C 中使用 sigaction 启用信号处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5113545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:52:57  来源:igfitidea点击:

Enable a signal handler using sigaction in C

c

提问by txs

  struct sigaction psa;

I have enabled my signal handler in the main function as shown below:

我在主函数中启用了我的信号处理程序,如下所示:

    memset (&psa, 0, sizeof (psa));
    psa.sa_handler = pSigHandler;
    sigaction (SIGALRM, &psa, NULL);
    sigaction(SIGVTALRM, &psa, NULL);
    sigaction(SIGPROF, &psa, NULL);

My signal handler is like this:

我的信号处理程序是这样的:

static void pSigHandler(int signo){
    printf("Pareint signum: %d", signo);// debug
    switch (signo) {
        case SIGALRM:
            printf("P SIGALRM handler");//debug
            break;
        case SIGVTALRM:
            printf("P SIGVTALRM handler");//debug
            break;
        case SIGPROF:
            printf("P SIGPROF handler");//debug
            break;
        default: /*Should never get this case*/
            break;
    }
    return;
}

Now my question may be obvious to some people, why didn't I see the printed debug lines when I run this? In fact, nothing was printed. Thank you very much for helping me to understand this. I'm running it on Linux, used Eclipse to program.

现在我的问题对某些人来说可能很明显,为什么我在运行它时没有看到打印的调试行?事实上,什么都没有打印。非常感谢您帮助我理解这一点。我在 Linux 上运行它,使用 Eclipse 进行编程。

回答by Thomas Dignan

#include <stdio.h>
#include <signal.h>

static void pSigHandler(int signo){
    switch (signo) {
            case SIGTSTP:
            printf("TSTP");
            fflush(stdout);
            break;
    }
}

int main(void)
{
    struct sigaction psa;
    psa.sa_handler = pSigHandler;
    sigaction(SIGTSTP, &psa, NULL);
    for(;;) {}
    return 0;
}

Because you need to fflush(stdout)

因为你需要 fflush(stdout)

try with C-z

试试 Cz

I'm not even sure if it's safe to use stdio in a signal handler though.

我什至不确定在信号处理程序中使用 stdio 是否安全。

Update: http://bytes.com/topic/c/answers/440109-signal-handler-sigsegv

更新:http: //bytes.com/topic/c/answers/440109-signal-handler-sigsegv

According to that link, you should not do this.

根据该链接,您不应该这样做。