Printf is not working in C signal handler

混江龙づ霸主 提交于 2019-12-28 03:08:05

问题


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

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

kill -s SIGINFO <pid_of_my_process>

Signal is delivered, c is incremented .. but the fprintf doesn't happen.

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


回答1:


In short : you cannot use safely printf within signal handler

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

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




回答2:


You may need to fflush stderr to get the message to write before the program exits.



来源:https://stackoverflow.com/questions/9547949/printf-is-not-working-in-c-signal-handler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!