关于sigwait()的模糊描述

If no signal in
set is pending at the time of the call, the thread shall be
suspended until one or more becomes
pending. The signals defined by set
shall have been blocked at the
time of the call to sigwait(); otherwise, the behavior is undefined.
The effect of sigwait() on the signal
actions for the signals in set is
unspecified.

这是真的含糊不清,这里有什么区别呢?

而关于如何选择sigwait和sigaction之间的结论是不清楚的:

In summary, when it is necessary for
code run in response to an
asynchronous signal to notify a
thread, sigwait() should be used to
handle the signal. Alterna-
tively, if the implementation provides semaphores, they also can be
used, either following sigwait() or
from within a signal handling routine
previously registered
with sigaction().

有人可以使sigwait的理由更理性吗?

每个进程都有一个与之相关联的信号掩码,它定义了被阻塞的一组信号.信号掩码可以查询或设置为setprocmask(2)(单线程代码)和pthread_sigmask(3)(用于多线程代码).

无论何时通过kill(2)raise(3)显示信号,或通过某些其他机制(例如提高SIGSEGV的分段故障),信号将针对当前信号掩码进行检查.如果信号未被阻塞,则立即执行:如果设置了相应的信号处理程序,否则将运行默认动作(通常退出异常状态或忽略它).如果信号被信号屏蔽阻塞,则信号的状态被设置为挂起,程序继续执行.

所以请考虑以下示例程序:

#include <signal.h>
#include <stdio.h>

void on_sigusr1(int sig)
{
  // Note: Normally, it's not safe to call almost all library functions in a
  // signal handler, since the signal may have been received in a middle of a
  // call to that function.
  printf("SIGUSR1 received!\n");
}

int main(void)
{
  // Set a signal handler for SIGUSR1
  signal(SIGUSR1, &on_sigusr1);

  // At program startup, SIGUSR1 is neither blocked nor pending, so raising it
  // will call the signal handler
  raise(SIGUSR1);

  // Now let's block SIGUSR1
  sigset_t sigset;
  sigemptyset(&sigset);
  sigaddset(&sigset, SIGUSR1);
  sigprocmask(SIG_BLOCK, &sigset, NULL);

  // SIGUSR1 is now blocked, raising it will not call the signal handler
  printf("About to raise SIGUSR1\n");
  raise(SIGUSR1);
  printf("After raising SIGUSR1\n");

  // SIGUSR1 is now blocked and pending -- this call to sigwait will return
  // immediately
  int sig;
  int result = sigwait(&sigset, &sig);
  if(result == 0)
    printf("sigwait got signal: %d\n", sig);

  // SIGUSR1 is now no longer pending (but still blocked).  Raise it again and
  // unblock it
  raise(SIGUSR1);
  printf("About to unblock SIGUSR1\n");
  sigprocmask(SIG_UNBLOCK, &sigset, NULL);
  printf("Unblocked SIGUSR1\n");

  return 0;
}

输出:

SIGUSR1 received!
About to raise SIGUSR1
After raising SIGUSR1
sigwait got signal: 30
About to unblock SIGUSR1
SIGUSR1 received!
Unblocked SIGUSR1
翻译自:https://stackoverflow.com/questions/6326290/about-the-ambiguous-description-of-sigwait

转载注明原文:关于sigwait()的模糊描述