printf的是不是在C信号处理工作 [英] Printf is not working in C signal handler

查看:112
本文介绍了printf的是不是在C信号处理工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题code第(最小化的情况下):

Code in question first (minimized case):

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

int counter = 0;

void react_to_signal(int n) {
    fprintf(stderr, "Caught!\n");
    counter++;
}

int main(int argc, char** argv) {

    signal(SIGINFO, react_to_signal);

    while (1) {
        printf("%d\n", counter);
    }

    return 0;
}

我运行code,它循环,因为它应该,在另一个shell打印出0,然后..

I run the code, it loops as it should, printing out 0. Then in another shell..

kill -s SIGINFO <pid_of_my_process>

信号传递, C 递增..但 fprintf中不会发生。

为什么会这样?在什么样的环境/背景做处理code运行?我在哪里可以在这读了?

Why is this so? In what environment/context does handler code run? Where can I read up on this?

推荐答案

在短期:你不能使用的安全的printf的信号处理程序中

In short : you cannot use safely printf within signal handler

有授权功能列表在信号处理程序手册页中的异步信号安全的部分。没有fprintf中在它。

There's a list of authorized functions in signal handler man page, in Async-signal-safe section. There is not fprintf in it.

这是因为这个功能不是的折返的,主要是因为它可以使用malloc和free。
请参见这个帖子了详细的解释。

That's because this function is not reentrant, mainly because it can use malloc and free. See this post for a detailed explanation.

这篇关于printf的是不是在C信号处理工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆