2

I heard that printf is not safe to call in a signal handler so why is that and what exactly is the consequences of doing so since I tried calling it several times with different signals and it seems to be ok. So what exactly I missed here.

  • And what makes a function safe to call in a signal handler ?.
void signal_handler(int signal){
    printf("Got signal :%d", signal);
}
KMG
  • 1,433
  • 1
  • 8
  • 19
  • 2
    "Seems to be okay" and "guaranteed to not cause any problems" are worlds apart. The problem seems to relate to re-entrant `printf` calls, as in receiving a signal in the middle of doing another `printf`. See [this answer](https://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler). – tadman Aug 18 '20 at 02:39
  • 2
    The signal could interrupt `malloc()` while the memory state is inconsistent, and then `printf()` could attempt to allocate more memory, and all hell could break loose. Basically, it isn't safe because the standards do not require it to be safe. You may get away with it a lot of the time — right up until you don't get away with it. Don't play with fire; you'll get burned. – Jonathan Leffler Aug 18 '20 at 02:47
  • @JonathanLeffler And what about static variables does printf use them or the problem is just with malloc, I mean if it is just malloc printing small amounts wouldnt cause printf to call malloc, but static variables would be a different story ? – KMG Aug 18 '20 at 02:52
  • There could be static variables in use — `stdout` for example, and locale information. There could be other activity by `printf()` than just memory allocation that causes trouble — locking the stream, for example. Standard C limits what you can do in a signal handler drastically. POSIX is a lot more generous, but still doesn't allow `printf()` to be called — though you could use `write()`. – Jonathan Leffler Aug 18 '20 at 02:56
  • 2
    Real-world example of possible consequences - we had a system that worked with Access databases. There was a signal handler that called `printf`. Somehow during the signal handling process `stderr` got mapped to the `.mdb` file, so all our error messages overwrote the database, hosing it beyond repair. – John Bode Aug 18 '20 at 03:19
  • @JohnBode I guess you could write that into the duplicate and tell how you fixed it :'D – Antti Haapala -- Слава Україні Aug 18 '20 at 05:56

0 Answers0