JayJona
JayJona

Reputation: 502

Is it safe to call fprintf() on a signal handler?

In my programm i've something like this

#include "mylib.h"
void signalsHandler(int signum){
    switch(signum){
        case SIGUSR1:{
            //open file.txt with write(O_CREAT | O_APPEND)
            //call the function that use fprintf() and write on file.txt

        }
        default: {
            abort();
        }
    }
}

and the main is like

struct sigaction s;
memset(&s,0,sizeof(s));
s.sa_handler=signalsHandler;
s.sa_flags=SA_RESTART;
sigaction(SIGUSR1,&s,NULL);

It is safe to call a function on mylib.h that use fprintf() to write on a file? According to here I can only call write

Upvotes: 5

Views: 1401

Answers (1)

dbush
dbush

Reputation: 224062

fprintf is not safe to call in a signal handler, due in part to the buffering capabilities for FILE objects.

What you should do is set a global flag in the signal handler, then check that flag elsewhere in your code and act accordingly.

Upvotes: 7

Related Questions