gpt4 book ai didi

c - sigsuspend(),替换设置还是添加?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:52 25 4
gpt4 key购买 nike

根据 sigsuspend() 的手册页,它将用第一个参数替换当前信号掩码集。在APUE中,我看到了一个例子如下。代码可能有点太长了,但我不想错过任何东西。

int pr_mask(char *s)
{
sigset_t sigset;

sigprocmask(0, NULL, &sigset);

printf("%s: ", s);

if(sigismember(&sigset, SIGINT)) printf("SIGINT ");
if(sigismember(&sigset, SIGQUIT)) printf("SIGQUIT ");
if(sigismember(&sigset, SIGUSR1)) printf("SIGUSR1 ");
if(sigismember(&sigset, SIGALRM)) printf("SIGALRM ");
/* ..... */

printf("\n");
return 0;
}

void sig_quit(int signo)
{
pr_mask("in sig quit");
}

int main()
{
sigset_t new, old, tempset;

signal(SIGQUIT, sig_quit);

sigemptyset(&tempset);
sigaddset(&tempset, SIGINT);

sigemptyset(&new);
sigaddset(&new, SIGQUIT);
sigprocmask(SIG_BLOCK, &new, &old);

pr_mask("in critical section");
/* critical section */

sigsuspend(&tempset);
pr_mask("after return form sigsuspend");

sigprocmask(SIG_UNBLOCK, &new, NULL);
pr_mask("program exit");

return 0;
}

输出是:

in critical section: SIGQUIT 
in sig quit: SIGINT SIGQUIT
after return form sigsuspend: SIGQUIT
program exit:

问题出在第二行。 SIGQUIT 仍在信号掩码集中。

它是否应该只是 SIGINT,因为 sigsuspend 已经用 tempset 替换了信号掩码,它被设置为仅 SIGINT

最佳答案

在执行 SIGQUIT 处理程序时,SIGQUIT 本身被阻塞。这是为了避免意外重新进入处理程序...

来自POSIX spec for sigaction (你真的应该使用它而不是 signal):

When a signal is caught by a signal-catching function installed by sigaction(), a new signal mask is calculated and installed for the duration of the signal-catching function (or until a call to either sigprocmask() or sigsuspend() is made). This mask is formed by taking the union of the current signal mask and the value of the sa_mask for the signal being delivered, and unless SA_NODEFER or SA_RESETHAND is set, then including the signal being delivered.

POSIX spec for signal不太具体:

When a signal occurs, and func points to a function, it is implementation-defined whether the equivalent of a:

signal(sig, SIG_DFL);

is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed.

因此,操作系统在信号处理功能期间简单地将信号添加到掩码是合法的,显然这就是 Linux 所做的。

关于c - sigsuspend(),替换设置还是添加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729147/

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