gpt4 book ai didi

c - 关于sigwait()的模糊描述

转载 作者:IT王子 更新时间:2023-10-29 00:23:42 27 4
gpt4 key购买 nike

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.

这真是模棱两可,这里的pendingblock有什么区别?

而它关于如何在sigwaitsigaction之间进行选择的结论一点也不清楚:

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),都会根据当前信号掩码检查信号.如果信号未被阻塞,则立即对其进行操作:如果已设置,则调用相应的信号处理程序,否则将运行默认操作(通常以异常状态退出或忽略它)。如果信号被信号掩码阻塞,则信号的状态设置为pending,程序继续执行。

因此请考虑以下示例程序:

#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

关于c - 关于sigwait()的模糊描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6326290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com