Determine if a function is async-signal-safe (can be called inside a signal handler)

风格不统一 提交于 2019-12-22 06:30:07

问题


My questions are:

  1. Is there a way to conclusively determine if a function is async-signal-safe if you don't have access to its implementation?
  2. If not, is there a way to test if function would be async-signal-safe enough to call from a signal handler?

If you reads the man pages of signal() or sigaction(), you get a list of async-signal-safe functions (functions that can be safely called inside a signal handler). However, I believe that this list is not exhaustive. For example, the following page http://linux.die.net/man/7/signal, under the Async-signal-safe functions header, reads:

POSIX.1-2004 (also known as POSIX.1-2001 Technical Corrigendum 2) requires an implementation to guarantee that the following functions can be safely called inside a signal handler:

And then it proceeds to list the normal async-signal-safe functions listed in the man pages above. As I read it, it says "it requires", not "these are the only ones".

For example, this site says that back_trace_symbols_fd() is async-signal safe. That function obtains is data from dladdr() and it doesn't use malloc() like back_trace_symbols(), so it looks like it may be safe. Also, I did some testing, and the output struct of dladdr() contains char* variables, but these are NOT malloc'ed at runtime. The char string they point to exists at run-time even before dladdr() is called.

Any thoughts or ideas that can point me in the right direction are appreciated.


回答1:


If you don't have access to the function's implementation, you can look at the manual page. If the manual page doesn't say it is async-safe, and the POSIX standard doesn't say it is async-safe, the only safe conclusion is "it is not async-safe" (coupled with "do not use it").

There is no 100% reliable way to test whether a function is async-safe. Remember, testing can only show the presence of bugs, not their absence (Dijkstra). The mere fact that you don't manage to tickle the function into misbehaving under test may simply mean that your testing is not adequate (but rest assured, the important customer who you can't afford to offend will immediately and accidentally devise a devastatingly effective test that demonstrates that the function is not async-safe almost as soon as you release the code with the faulty assumption).




回答2:


What are you hoping to achieve in the signal handler? You should consider whether it is the right place for it. It is probably best to follow the advice of the man page:

In general, signal handlers should do little more  
than set a flag; most other actions are not safe.


来源:https://stackoverflow.com/questions/9014560/determine-if-a-function-is-async-signal-safe-can-be-called-inside-a-signal-hand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!