Handle two consequent SIGTERMs
There is a daemon which has two threads: th1, th2. th2 reads a socket using read(2)
.
If I kill the daemon with SIGTERM
, th1 catches and handles the signal (sets the termination flag), after that the daemon destructor get called, it calls pthread_kill(th2, SIGTERM)
. However, the second thread does not receive SIGTERM
, so it does not get killed (when the socket receives data and gets out from read()
, it finishes execution, as the termination flag has been set).
If I call pthread_kill(th2, SIGUSR2)
, and then pthread_kill(th2, SIGTERM)
, everything finishes correctly. Thus, it seems that UNIX doesn't allow sending identical signals consequently.
Does this behaviour depend on operating system? Can we ensure that the specified thread receives 开发者_如何学编程SIGTERM
from another thread?
Unix does allow sending multiple consecutive signals to a process, although if the signals are sent too close together, or an additional signal was been sent to the process before an already pending signal was delivered, then multiple signals can be concatenated into a single signal event.
Also keep in mind that while pthread_kill()
sends a signal to a given thread to be handled, the actual handling of the signal has a global effect (i.e., signal handlers are per-process, not per-thread).
You may also want to look into explicitly calling pthread_cancel()
since read()
is a valid cancellation point. You can, if needed, add a cancellation handler, as well as block the cancellation-state of a thread if you are using functions that are not cancellation-safe. You can read some tips on using pthread_cancel()
here.
A relatively old-school but effective approach is to use select() and a pipe to re-dispatch signals to all threads. (You select() on your blocking handle an the pipe read handle).
精彩评论