我可以检查待处理信号并立即执行它们吗
我想做的是只处理代码中某些已知点的信号。因此,在这些点上,我将检查待处理信号并立即执行其处理程序。
我知道我可以使用 sigprocmask 来阻止信号,然后再解除阻止,但仍然如此,信号将在解除阻止后的任何时间点传递,这是我不想要的。我想在代码中的特定位置精确执行信号处理程序。换句话说,我想让信号处理同步。
有没有可能的方法来实现我想要做的事情?
What I want to do is to only handle signals at some known points in my code. So at those points I will check for a pending signal and execute its handler immediately.
I know I can use sigprocmask
to block a signal and later unblock it, but sill in that way, the signal will be delivered at any point in time after unblocking, which I don't want. I want to execute the signal handler precisely at a specific location in my code. In other words, I want to make signal handling synchronous.
Is there a possible way to achieve what I'm trying to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 sigwait 系统调用系列来获取任何待处理的阻塞信号。不过,不可能同时等待信号和其他类型的事件,如果您不想在 sigwait 中阻塞,您可以首先使用
sigpending
检查是否有待处理的信号。如果您的应用程序使用事件驱动设计,则通常在运行循环中会有多个 fd。对于这种情况,您应该使用写入
管道
的信号处理程序。该信号将异步传递,但随后将作为另一个需要处理的 fd 出现在您的运行循环中。You can fetch any pending blocked signal using the
sigwait
family of syscalls. It's not possible to wait for both signals and other types of events concurrently though, if you do not want to block in sigwait you can first check if there's pending signals usingsigpending
.If you're using an event driven design for your application you'll typically have several fds in a run loop. For that situation you should instead use a signal handler which writes to a
pipe
. The signal will be delivered asynchronously but will then appear in your run loop as just another fd that needs processing.如果我理解正确,您可以简单地使用 sigwait 清除每个待处理信号,然后直接调用信号处理函数。
在代码中想要处理和清除待处理信号的地方,您可以使用 sigpending 来检查是否有信号等待,然后重复调用 sigwait 来清除待处理信号,手动调用信号处理函数来执行所需的操作。
If I understand you correctly you can simply use
sigwait
to clear each of the pending signals and then call the your signal handler function directly.At the points in your code where you want to handle and clear pending signals you can use
sigpending
to check if there are signals waiting and then repeatedly callsigwait
to clear the pending signals, manually calling a signal handling function to perform the required action.当您取消屏蔽任何待处理信号时,它们将立即传递。只需在您想让它们被传送的地方取消屏蔽/重新屏蔽即可。如果您使用线程,请注意异步信号(例如从
kill
获得的信号)可以发送至任何已解除阻塞的线程。Any pending signals will be delivered immediately when you unmask them. Just unmask/remask at the point where you want to let them be delivered. If you are using threads be aware that asynchronous signals (like those you get from
kill
) can go to any thread that has them unblocked.