Reputation: 14990
We recently had a discussion at work about signal handlers in C (Unix enviornment).
Someone mentioned that
(f)printf() is certainly thread-safe but not signal-handler safe.
What does the above statement mean? What aspect of (f)printf() make it not signal-handler safe? Is it because it accesses the stdout and stdin which are global and hence the function is not re-entrant?
Or is there some other aspect which I am missing?
Upvotes: 2
Views: 426
Reputation: 1283
As mentioned in here: http://www.gnu.org/software/libc/manual/html_node/Nonreentrancy.html#Nonreentrancy
If a function uses and modifies an object that you supply, then it is potentially non-reentrant; two calls can interfere if they use the same object.
In your case that object is stdout
. When a signal arrives in the middle of a (f)printf()
and if you use (f)printf
in handler, both data could be corrupted as they operate on the same stream, stdout
. Reentrancy is the root cause in that case. Even if you use the stream in just signal handler, two signal handlers can interfere.
Upvotes: 3
Reputation: 249263
There is actually fairly little that is legal to do in a signal handler directly. Instead, one must usually set some flag or trigger to do the real work outside the signal handling context. While handling a signal, the only functions you can call are those which are "async signal safe," which is described in detail here: What constitutes asynchronous-safeness
Upvotes: 5