当已经在信号处理程序中时接收到信号会发生什么? [英] What happens when a signal is received while already in a signal handler?
问题描述
我有一个父进程,它产生了几个子进程.我想知道何时通过注册SIGCHLD
信号处理程序退出任何子进程.
I have a parent process spawning several child processes. I want to know when any child process exits by registering a SIGCHLD
signal handler.
问题是,如果在父进程已经在信号处理程序中的情况下又收到另一个SIGCHLD
(或任何其他信号),会发生什么情况?
The question is, what happens if another SIGCHLD
(or any other signal) is received, while the parent process is already in a signal handler?
我可以想到以下结果:
- 信号被忽略
- 该信号已排队,将在当前处理程序返回后立即进行处理
- 与主程序一样,当前处理程序又被中断
哪个是正确的?
推荐答案
在您的具体示例中(接收到相同的信号),信号在信号处理程序完成之后被传递(因此,第2点是正确的).但是请注意,您可能会丢失"信号.
In your concrete example (the same signal being received), the signal is delivered after the signal handler has finished (so bullet point #2 is correct). Note, however, that you may "lose" signals.
这样做的原因是,当信号在其处理程序中时,它被阻止了.被阻止的信号被设置为未决,但未排队.术语待定"表示操作系统记住有一个信号等待下一次机会传递,而未排队"表示操作系统通过在某处设置标志来实现此目的,而不是通过保留有关如何操作的确切记录来进行.许多信号已经到达.
The reason for that is that while a signal is being inside its handler, it is blocked. Blocked signals are set to pending, but not queued. The term "pending" means that the operating system remembers that there is a signal waiting to be delivered at the next opportunity, and "not queued" means that it does this by setting a flag somewhere, but not by keeping an exact record of how many signals have arrived.
因此,在处理程序中,您可能会再收到2或3(或10)个SIGCHLD
,但只能看到一个(所以在某些情况下,项目符号#1 也可以是) ).
Thus, you may receive 2 or 3 (or 10) more SIGCHLD
while in your handler, but only see one (so in some cases, bullet point #1 can be correct, too).
请注意,可以传递给sigaction
的几个标志会影响默认行为,例如SA_NODEFER
(防止阻塞信号)和SA_NOCLDWAIT
(在某些系统上可能根本不产生信号).
Note that several flags that you can pass to sigaction
can affect the default behaviour, such as SA_NODEFER
(prevents blocking signal) and SA_NOCLDWAIT
(may not generate signal at all on some systems).
当然,现在,如果您收到其他类型的信号,则不能保证它不会中断您的处理程序.因此,最好不要使用非信号安全功能.
Now of course, if you receive a different type of signal, there's no guarantee that it won't interrupt your handler. For that reason, one preferrably doesn't use non signal safe functions.
这篇关于当已经在信号处理程序中时接收到信号会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!