简体   繁体   English

sem_wait和信号处理程序

[英]sem_wait and signal handler

Why sem_wait cannot be used inside a signal handler (particularly SIGSEGV signal which is per thread)? 为什么sem_wait不能在信号处理程序中使用(特别是每个线程的SIGSEGV信号)? Can someone give me an example scenario where it will crash the application? 有人可以给我一个示例场景,它会使应用程序崩溃吗? I guess sem_wait is both reentrant and thread safe , so what is the problem here? 我猜sem_wait可重入的线程安全的 ,所以这里有什么问题? Why is it not async safe ? 为什么它不是异步安全的

Async safe is a much stricter requirement than thread safe. 异步安全是一个比线程安全更严格的要求。 You can write thread safe code using primitives to protect global data with critical sections. 您可以使用基元编写线程安全代码,以保护关键部分的全局数据。 Signal handlers can't rely on this. 信号处理程序不能依赖于此。 For example, you could be inside a critical section within sem_wait, and simultaneously do something that causes a segfault. 例如,您可能位于sem_wait内的关键部分内,同时执行导致段错误的操作。 This would break the thread-safe protections of sem_wait. 这会破坏sem_wait的线程安全保护。

What if the application receives a signal while the value of the semaphore is zero, and the thread that receives the signal happens to be the one which is supposed to increment the semaphore value (sem_post)? 如果应用程序在信号量的值为零时接收到信号,并且接收信号的线程恰好是应该增加信号量值(sem_post)的线程,该怎么办? If you then call sem_wait in the signal handler, the process will deadlock, no? 如果你在信号处理程序中调用sem_wait,那么进程会死锁,不是吗?

Another argument could of course be that if sem_wait is not on the list of async-signal-safe functions, the implementation is free to invoke nasal demons. 另一个论点当然可能是,如果sem_wait不在异步信号安全函数列表中,则实现可以自由地调用鼻子恶魔。

sem_wait cannot be used in a signal handler for this reason: 由于这个原因,sem_wait不能在信号处理程序中使用:

Thread A is calls sem_wait on sem1. 线程A在sem1上调用sem_wait。 When thread A is done, it posts to sem1. 线程A完成后,它会发布到sem1。 However, before it can finish the signal is received and then handler is entered, calling sem_wait on sem1. 但是,在它完成之前,接收信号然后输入处理程序,在sem1上调用sem_wait。 Since A is the one that would post to sem1, the handler will never return and you will have deadlock. 因为A是发布到sem1的那个,所以处理程序永远不会返回,你将遇到死锁。 This is why it is a good rule to never wait on anything in a signal handler. 这就是为什么永远不要等待信号处理程序中的任何事情的原因。 The problem, ASFAIK, has more to do with deadlock than crashing. 问题,ASFAIK,更多的是死锁而不是崩溃。

Also, this violates the ideal purpose of a signal handler, which is to handle an external interrupt and then get back to what you were doing quickly. 此外,这违反了信号处理程序的理想目的,即处理外部中断然后快速恢复到您正在做的事情。

Lastly, isn't it a better goal to rid yourself of the SIGSEGV instead of handling it? 最后,摆脱SIGSEGV而不是处理它不是一个更好的目标吗?

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

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