Immort Immort - 4 months ago 22
C++ Question

Signal handling in mutlti-threaded process

I have a basic problem of handling signal in a multi-threaded process.

In my code, I create one sub-thread from the main thread, to listen to a

SIGALRM
which will be later trigger by main thread (using other function like
timer_create
gives me the same result, so please don't focus on this).

The problem is, instead of catching the signal, the whole process terminated with a strange "Alarm clock" output on the console.

This is my code:

#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <csignal>

using namespace std;

void* run_something(void* args){
//unblock the SIGALRM to be catched
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig, SIGALRM);
sigprocmask(SIG_UNBLOCK, &sig, NULL); //tried with pthread_sigmask

//wait for SIGALRM
int catchedSig;
sigwait(&sig, &catchedSig);
cout<<"in sub-thread, SIGALRM catched, return"<<endl;
}

int main(int argc, char** argv){
//block SIGALRM in main thread
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig, SIGALRM);
sigprocmask(SIG_BLOCK, &sig, NULL);

//create new thread
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&thread, &attr, run_something, NULL);

//trigger SIGARLM after 2s
alarm(2); //tried with timer_create/sigevent

//wait
cout<<"in main thread, waiting for sub-thread to terminate"<<endl;
pthread_join(thread, NULL);
cout<<"in main thread, terminating"<<endl;

return EXIT_SUCCESS;
}


Expected result


  • in main thread, waiting for sub-thread to terminate

  • in sub-thread,
    SIGALRM
    getting caught, return

  • in main thread, terminating



Observed result


  • in main thread, waiting for sub-thread to terminate

  • Alarm clock



Additional info:
I'm using g++ (Debian 5.4.0-4) 5.4.0 20160609.

Answer

Your run_something thread unblocks SIGALRM before calling sigwait for that signal, but this is undefined behavior. sigwait removes a signal from the set of pending (i.e., blocked) signals.

Don't unblock in your thread and you'll see the behavior you expect.