Linked by Eugenia Loli-Queru on Thu 1st Dec 2005 17:24 UTC
Thread beginning with comment 67806
To read all comments associated with this story, please click here.
To read all comments associated with this story, please click here.
RE: printf in a signal handler
by james_parker on Fri 2nd Dec 2005 22:52
in reply to "printf in a signal handler"
This is generally true, although a version of printf could be written that may be called safely. (I've done that before to get past such issues in code I've inherited before cleaning it up later).
I took its use to be "generally illustrative" rather than detailed recommended practice (I suspect the author wasn't considering the printf call to be part of the technique but used it as shorthand for saying "print information here").
The author should have recognized this, though; and included a warning about this practice, or simply left the print example as a comment.






Member since:
many errors in this writeup. but you can also see these errors if you google for 'printf signal handler'. many people giving the same bad, bad, bad advice.
you cannot call printf in a signal handler.
signal handlers are like interrupt handlers; they could happen at any time while the main code block is doing who knows what; even internally inside printf, malloc, stdio, who knows what.
there is a definate set of rules as to what you can do in a signal handler.
1) POSIX and SU define a list of safe functions. some other systems have additional functions which are safe; depending on how portable you want to be.
2) any global variable accessed from inside the signal handler should be of type 'volatile sig_atomic_t' to ensure that reads or writes to/from it happens safely and atomically without compiler-level caching. this matters even more on RISC processors.
for further explanations, please see the following manual page which makes an attempt to detail some of the issues:
http://www.openbsd.org/cgi-bin/man.cgi?query=signal&apropos=0&sekti...
(One interesting thing is that OpenBSD has a signal handler safe snprintf, which would allow you to actually replace many printf type problems with a snprintf + write combination).
it should scare us all when vendors publish articles which show they know so little about programming in the unix environment. but a google search will show how many other people get this wrong.
and please go read some actual code to see how bad the real situation is...