The Linux Programming Interface

(nextflipdebug5) #1
Threads: Further Details 685

As with pthread_kill(), sig specifies the signal to be sent, and thread identifies the target
thread. The value argument specifies the data to accompany the signal, and is used
in the same way as the equivalent argument of sigqueue().

The pthread_sigqueue() function was added to glibc in version 2.11 and requires
support from the kernel. This support is provided by the rt_tgsigqueueinfo() sys-
tem call, which was added in Linux 2.6.31.

33.2.4 Dealing with Asynchronous Signals Sanely


In Chapters 20 to 22, we discussed various factors—such as reentrancy issues, the
need to restart interrupted system calls, and avoiding race conditions—that can make
it complex to deal with asynchronously generated signals via signal handlers. Further-
more, none of the functions in the Pthreads API is among the set of async-signal-safe
functions that we can safely call from within a signal handler (Section 21.1.2). For
these reasons, multithreaded programs that must deal with asynchronously gener-
ated signals generally should not use a signal handler as the mechanism to receive
notification of signal delivery. Instead, the preferred approach is the following:

z All threads block all of the asynchronous signals that the process might receive.
The simplest way to do this is to block the signals in the main thread before any
other threads are created. Each subsequently created thread will inherit a copy
of the main thread’s signal mask.
z Create a single dedicated thread that accepts incoming signals using sigwaitinfo(),
sigtimedwait(), or sigwait(). We described sigwaitinfo() and sigtimedwait() in Sec-
tion 22.10. We describe sigwait() below.

The advantage of this approach is that asynchronously generated signals are
received synchronously. As it accepts incoming signals, the dedicated thread can
safely modify shared variables (under mutex control) and call non-async-signal-safe
functions. It can also signal condition variables, and employ other thread and pro-
cess communication and synchronization mechanisms.
The sigwait() function waits for the delivery of one of the signals in the signal
set pointed to by set, accepts that signal, and returns it in sig.

#define _GNU_SOURCE
#include <signal.h>

int pthread_sigqueue(pthread_t thread, int sig, const union sigval value);
Returns 0 on success, or a positive error number on error

#include <signal.h>

int sigwait(const sigset_t *set, int *sig);
Returns 0 on success, or a positive error number on error
Free download pdf