问题描述
我正在尝试创建一个阻止信号SIGUSR1的程序,并且它将取消阻止该信号.在中间,我想使用sigpending
阻止信号.但是它总是说信号没有被阻塞,在应该被阻塞的情况下我可以使用该信号.这是我的代码.
I'm trying to create a program that blocks the signal SIGUSR1 and the it unblocks the signal.In the middle I want to see that the signal is blocked using sigpending
. But it always says that the signal isn't blocked, and I can use the signal when it's supposed to be blocked.This is the code that I have.
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
static void signals(int signaln)
{
switch (signaln) {
case SIGUSR1:
printf("Signal SIGUSR1\n"); break;
}
return;
}
main()
{
sigset_t set,set2;
struct sigaction sigs;
sigs.sa_handler = signals;
sigemptyset(&sigs.sa_mask);
sigs.sa_flags=SA_ONESHOT;
sigaction(SIGUSR1, &sigs,0);
sigemptyset(&set);
sigemptyset(&set2);
sigaddset(&set,SIGUSR1);
if(sigprocmask(SIG_BLOCK, &set, NULL)==0){
printf("Blocking SISGUSR1...\n");
}
sigpending(&set2);
if (sigismember(&set2,SIGUSR1)==1)
{
printf("The signal is blocked\n"); //it should print this
}
wait(2);
kill(getpid(),SIGUSR1); //the signal shouldn't work
wait(2);
if(sigprocmask(SIG_UNBLOCK, &set, NULL)==0){
printf("Unblocking SIGUSR1\n");
}
}
有人可以帮我吗?
推荐答案
sigpending
不会告诉您信号是否被阻止.它告诉您是否正在等待发送信号. (即,信号被 阻止了,并且已经发送了一个信号.)
sigpending
doesn't tell you whether a signal is blocked. It tells you whether a signal is waiting to be delivered. (i.e., the signal is blocked and one has been sent.)
此外,被阻止并不意味着信号将不会被传递;这意味着该信号现在将不再发送.因此,您可以发送信号,并且在信号被解除阻塞后将立即发送该信号.可能在调用sigprocmask(SIGUNBLOCKED...)
之后但在调用printf
之前,所以您可能会在看到取消阻止"消息之前看到已收到信号的消息.
Also, blocked doesn't meean that the signal won't be delivered; it means that the signal won't be delivered now. So you can send the signal, and it will be delivered as soon as the signal is unblocked; probably after the call to sigprocmask(SIGUNBLOCKED...)
but before the call to printf
, so you'll probably see the signal received message before you see the "unblocking" message.
这篇关于如何在C中阻止信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!