The effects of signal() in a multithreaded process are unspecified

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

I did not know this, and I find this very surprising:

Continuing reading the manual page, the very first note under the NOTES section is this:

The effects of signal() in a multithreaded process are unspecified.

This is called Unspecified Behavior. What it means is that standard does not say anything as for how the function should behave in a multi-threaded environment. Therefore, it may exhibit a different behavior on different systems including different versions of the same system, at discretion of those who implement it. Your mileage may vary.

Even if your code does not explicitly use multiple threads, you are still in danger — it might be used as part of a bigger program in multi-threaded environment. But even if that’s not that case — hey, tomorrow you might want to do that. Do you really want to screw yourself upfront by using this bad signal() function? Think twice.

Asynchronicity & Reentrancy

Signals are asynchronous by their nature. Another signal may be delivered to the process while the previous signal is still being “processed”. Therefore, signal handler must not introduce unwanted side effects, must be fully reentrant and cannot use any non-reentrant code — neither explicitly nor implicitly. Now take a quick look at the famous example mentioned at the beginning — there is a nice printf() right in the signal handler code. This is a life threatening piece of code because printf() is non-reentrant. In other words, it is possible that printf() function will get interrupted before it finishes and get called again as part of another signal handler. If that case the program will simply deadlock.

Post external references

  1. 1
    http://741mhz.com/signal-handler/
Source