简体   繁体   中英

sigwait() does not work in multithreaded program

I'm trying to write a multithreaded program which one thread (variable thread in below) is responsible to any asynchronous signals that might be set to this process.

I am facing thread that uses sigwait() but does not react to any signals have been sent to process. (like SIGUSR1 in below).

static void * signal_thread(void *arg = nullptr)
{
    int sig = -1;
    sigset_t sigset;
    sigfillset(&sigset);
    pthread_sigmask(SIG_BLOCK, &sigset, NULL);
    while(1)
    {
       int s = sigwait(&sigset, &sig);
       if(s == 0)
          printf("SIG %d recieved!...\n", sig);
       usleep(20);
    }
}

int main()
{
    sigset_t signalset;
    pthread_t thread;
    pthread_create(&thread, NULL, &signal_thread, nullptr);
    sigfillset(&signalset);
    pthread_sigmask(SIG_BLOCK, &signalset, NULL);

    while(1)
    {
       raise(SIGUSR1);
       usleep(20);
    }
}

The problem is concerned to two issues:

First, call of raise in main sent signal only to main thread not whole process.

Secondly, std::cout should be used instead of printf in signal_thread.

raise(sig) is the equivalent of calling pthread_kill(pthread_self(), sig) .

Since the main thread raise() s the signal, the SIGUSR1 will be generated for that thread and not for any other. Thus, your signal_thread will be unable to sigwait() for the USR1, which will be held pending for the thread that generated it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM