Which thread handles the signal? Which thread handles the signal? multithreading multithreading

Which thread handles the signal?


If you send a signal to a process, which thread in the process will handle this signal is undetermined.

According to pthread(7):

POSIX.1 also requires that threads share a range of other attributes (i.e., these attributes are process-wide rather than per-thread):
...
- signal dispositions
...

POSIX.1 distinguishes the notions of signals that are directed to the process as a whole and signals that are directed to individual threads. According to POSIX.1, a process-directed signal (sent using kill(2), for example) should be handled by a single, arbitrarily selected thread within the process.


If you want a dedicated thread in your process to handle some signals, here is an example from pthread_sigmask(3) shows you how to do it:

The program below blocks some signals in the main thread, and then creates a dedicated thread to fetch those signals via sigwait(3). The following shell session demonstrates its use:

$ ./a.out &[1] 5423$ kill -QUIT %1Signal handling thread got signal 3$ kill -USR1 %1Signal handling thread got signal 10$ kill -TERM %1[1]+  Terminated              ./a.out

Program source

#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <errno.h>/* Simple error handling functions */#define handle_error_en(en, msg) \        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)static void *sig_thread(void *arg){    sigset_t *set = arg;    int s, sig;   for (;;) {        s = sigwait(set, &sig);        if (s != 0)            handle_error_en(s, "sigwait");        printf("Signal handling thread got signal %d\n", sig);    }}intmain(int argc, char *argv[]){    pthread_t thread;    sigset_t set;    int s;   /* Block SIGQUIT and SIGUSR1; other threads created by main()       will inherit a copy of the signal mask. */   sigemptyset(&set);    sigaddset(&set, SIGQUIT);    sigaddset(&set, SIGUSR1);    s = pthread_sigmask(SIG_BLOCK, &set, NULL);    if (s != 0)        handle_error_en(s, "pthread_sigmask");   s = pthread_create(&thread, NULL, &sig_thread, (void *) &set);    if (s != 0)        handle_error_en(s, "pthread_create");   /* Main thread carries on to create other threads and/or do       other work */   pause();            /* Dummy pause so we can test program */}


Read carefully signal(7) & pthread(7) & pthread_kill(3) & sigprocmask(2) & pthread_sigmask(3) -which you could use (to block SIGINT in unwanted threads). Read also a pthread tutorial.

Avoid using signals to communicate or synchronize between threads. Consider e.g. mutexes (pthread_mutex_lock etc...) and condition variables (pthread_cond_wait etc...).

If one of the threads runs an event loop (e.g. around poll(2)...) consider using signalfd(2).