简体   繁体   English

(f)printf()线程安全,但不是信号处理程序安全

[英](f)printf() thread-safe but not signal-handler safe

We recently had a discussion at work about signal handlers in C (Unix enviornment). 最近,我们在工作中讨论了C(Unix环境)中的信号处理程序。

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? (f)printf()的哪个方面使其不安全处理信号? Is it because it accesses the stdout and stdin which are global and hence the function is not re-entrant? 是否因为它访问全局的stdout和stdin而函数不能重入?

Or is there some other aspect which I am missing? 还是我缺少其他方面?

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 处理信号时,唯一可以调用的功能是“异步信号安全”功能,此处将对其进行详细说明: 异步安全性的构成

As mentioned in here: http://www.gnu.org/software/libc/manual/html_node/Nonreentrancy.html#Nonreentrancy 如此处所述: 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 . 在您的情况下,该对象是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 . 当信号到达(f)printf()的中间时,并且如果在处理程序中使用(f)printf ,则这两个数据可能会因为在同一流stdout上进行操作而被破坏。 Reentrancy is the root cause in that case. 在这种情况下,重入是根本原因。 Even if you use the stream in just signal handler, two signal handlers can interfere. 即使仅在信号处理程序中使用流,两个信号处理程序也会干扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM