13

I have a parent process spawning several child processes. I want to know when any child process exits by registering a SIGCHLD signal handler.

The question is, what happens if another SIGCHLD (or any other signal) is received, while the parent process is already in a signal handler?

I can think of the following outcomes:

  • The signal is ignored
  • The signal is queued, and will be processed as soon as the current handler returns
  • The current handler is in turn interrupted, just like the main program

Which one is correct?

4

1 回答 1

7

在您的具体示例中(接收到相同的信号),在信号处理程序完成后传递信号(因此要点#2 是正确的)。但是请注意,您可能会“丢失”信号。

原因是当信号在其处理程序中时,它被阻塞了。阻塞信号设置为待处理,但不排队。术语“待处理”意味着操作系统记住有一个信号等待在下一个机会被传递,而“未排队”意味着它通过在某处设置一个标志来做到这一点,而不是通过准确记录如何许多信号已经到来。

因此,您SIGCHLD在处理程序中可能会收到 2 或 3 个(或 10 个)更多,但只能看到一个(因此在某些情况下,要点 #1也可能是正确的)。

请注意,您可以传递给的几个标志sigaction可能会影响默认行为,例如SA_NODEFER(防止阻塞信号)和SA_NOCLDWAIT(可能在某些系统上根本不生成信号)。

当然,如果您收到不同类型的信号,则不能保证它不会中断您的处理程序。出于这个原因,最好不要使用非信号安全功能。

于 2013-08-26T10:54:56.540 回答