0

I have a strange behavior where manpage and google didn't help out.

In my code I want to block / unblock SIGINT when SIGUSR2 is sent. For this I install the signal handler and prepare the set for mask in a function:

void installSignallHandler(){

    sBlock.sa_handler = handleBlock;
    sigemptyset(&sBlock.sa_mask);
    sigaddset(&sBlock.sa_mask, SIGUSR2);
    sBlock.sa_flags = 0;
    sigaction(SIGUSR2, &sBlock, NULL);

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

    // For some reason sigprocmask only works if it is called here the first time
    // sigprocmask(SIG_BLOCK, &signals_protected, NULL);
    // sigintBlocked = true;
}

Then if SIGUSR2 is sent this function is called:

void handleBlock(int signal){
    if(sigintBlocked){
        printf("Unblocking SIGINT ...\n");
        sigprocmask(SIG_UNBLOCK, &signals_protected, NULL);
        sigintBlocked = false;
    }
    else{
        printf("Blocking SIGINT ...\n");
        sigprocmask(SIG_BLOCK, &signals_protected, NULL);
        sigintBlocked = true;
    }
}

For testing I called it like this:

int main(int argc, char **argv) {
    installSignallHandler();
    while(1){
        printf("processing...\n");
        sleep(1);
    }
    return EXIT_SUCCESS;
}

Now the problem: The way I posted the code, sigprocmask takes no effect. But if I uncomment the two lines above, it works. So my two questions:

  1. Can you explain this behavior?
  2. What can I do to solve it? - I don't want to start with blocked signal.
4

1 回答 1

1

因为它是竞争条件。在 sig_handler 中设置 sigintBlocked,然后在 main 函数中进行验证,如果设置了则屏蔽信号。

此链接 在信号执行期间有更多信息 sigprocmask

于 2014-04-24T17:13:51.467 回答