Why does a sigaction handler not handle every signal even if the SA_NODEFER flag is set?

做~自己de王妃 提交于 2019-12-06 12:28:58

Basic UNIX signals do not queue — only one can be pending (for a given thread) at a time.

If two child processes terminate at effectively the same time and thus deliver their SIGCHLD at the "same" time, your process will have only one signal pending.

waiting in a loop after receipt of a SIGCHLD is a long-established technique to compensate for the fact that a SIGCHLD may be "lost". Move the "Child finished!\n" announcement to the loop that calls wait, and you'll have an accurate count.

UPDATE

If you must reap within your handler, you may call wait within the handler, since it is async-signal-safe:

static void CHLDHandler(int sig)
{
  static char child[] = "Child finished!\n";
  int save_errno = errno;

  while (waitpid((pid_t)-1, NULL, WNOHANG) > 0) {
    write(STDERR_FILENO, &child, sizeof(child) - 1);  // don't write the terminating NULL
  }

  errno = save_errno;
}

In this case I would not set SA_NODEFER, since another SIGCHLD might interrupt (EINTR) the waitpid or the write calls.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!