pthread_join from a signal handler

c, multithreading, posix, pthreads

Solution

Really, don't do that.

I can't find any reference suggesting `pthread_join` is async signal safe (and by default you should assume they are not).

But even if that was the case, what you are suggesting doing is fantastically ugly.

In your signal handler, just set a flag in a `sig_atomic_t` variable to say the signal has occurred. Then poll than regularly, and do the writing of stats or joining of threads outside the signal handler.

If you don't like the polling, another neat technique is the 'self-writing pipe'. Set a pipe up where the write end is written to by the signal handler (as `write` is async safe) and read in your main `select()` loop or whatever.

Problem

I have a capture program which in addition do capturing data and writing it into a file also prints some statistics.The function that prints the statistics ``` static void* report(void) { /*Print statistics*/ } ``` is called roughly every second using an ALARM that expires every second.So The program is like ``` void capture_program() { pthread_t report_thread; while (!exit_now ) { if (pthread_create(&report_thread,NULL,report,NULL)) { fprintf(stderr,"Error creating reporting thread! \n"); } /* Capturing code -------------- -------------- */ if(doreport) usleep(5); } } void *report(void *param) { while (true) { if (doreport) { doreport = 0 //access some register from hardware usleep(5) } } } ``` The expiry of the timer sets the `doreport` flag.If this flag is set `report()` is called which clears the flag.I am using usleep to alternate between two threads in the program.This seems to work fine. I also have a signal handler to handle SIGINT (i.e CTRL+C) ``` static void anysig(int sig) { if (sig != SIGINT) dagutil_set_signal_handler(SIG_DFL); /* Tell the main loop to exit */ exit_now = 1; return; } ``` My question: ``` 1) Is it safe to call pthread_join from inside the signal handler? 2) Should I use exit_now flag for the report thread as well? ```

Original source