Printf does not work in C signal handler

First code (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 you would expect, by printing 0. Then in another shell.

kill -s SIGINFO <pid_of_my_process>

The signal is delivered, cincreased, but fprintfdoes not occur.

Why is this so? In what environment / context does the handler code execute? Where can I read this?

+5
source share
2 answers

In short: you cannot use printf safely in a signal handler

It contains a list of authorized functions on the signal handler man page in the "Safe Signal" section. It does not have fprintf.

, , , malloc . . .

+14

fflush stderr, .

+1

All Articles