4

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

JayJona
  • 469
  • 1
  • 16
  • 41
  • 1
    No, it's not safe. – Shawn Feb 26 '19 at 14:07
  • 1
    The documentation is clear, if `foo` is not is the list of async-signal-safe then it's not safe to call `foo` from a signal handler. However if you do so, your program still _might_ appear to work fine under certain conditions. Don't do it. – Jabberwocky Feb 26 '19 at 14:08
  • Possible duplicate of [linux/glibc. Can I use fprintf in signal handler?](https://stackoverflow.com/questions/4554129/linux-glibc-can-i-use-fprintf-in-signal-handler) – Sander De Dycker Feb 26 '19 at 14:13
  • 1
    you might also be interested in : [How to avoid using printf in a signal handler?](https://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler) – Sander De Dycker Feb 26 '19 at 14:14
  • [Per the C standard](https://port70.net/~nsz/c/c11/n1570.html#note188): "Thus, a signal handler cannot, in general, call standard library functions." POSIX provides guarantees that you can call **some/a few** functions. – Andrew Henle Feb 26 '19 at 14:15

1 Answers1

6

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.

dbush
  • 205,898
  • 23
  • 218
  • 273