當一個非同步產生的 signal 送達某個 process 時,它將由 process 中某個 thread 來處理,系統將會根據每個 thread 的 signal mask 來決定誰是選中的 thread 。如果有超過一個以上的 thread,它們的 signal mask 對 signal 來說都是 unblocked,系統將任意的幫你選一個。雖然你可以經由設定 signal mask 來影響系統選 thread 的過程,但無法直接指定某個 thread 來處理某個指定的 signal。
下面演示 pthread_sigmask 的範例,每隔二秒發出 SIGALRM 一次,由這個範例得到幾個結論。
- 預設的 signal mask = 0,也就是所有的 signal 都是 unblocked。
- signal 對 threads 的選擇都是以 thread 產生的順序為則準,所以每次都是第一個 threads 被選中。
- main 算是第一個 thread,如果沒有在 main 中使用 pthread_sigmask 來 block signal,則所有的 signal 都會由 main thread 來處理。
- main 中使用 pthread_sigmask 要注意,如果在 pthread_create 前使用,後面的 threads 會繼承變更後的 signal mask。
Signal handling with multiple threads in Linux
|
Q: In Linux, what happens when a program (that possibly has multiple threads) receives a signal, like SIGTERM or SIGHUP? Which thread intercepts the signal? Can multiple threads get the same signal? Is there a special thread dedicated entirely to handling signals? If not, what happens inside the thread that is to handle the signal? How does the execution resume after the signal handler routine finishes? ANS: pthreads(7) describes that POSIX.1 requires all threads in a process share attributes, including:
complete_signal() routine has the following code block -- the comments are quite useful:
So, you see that you are in charge of where signals are delivered:If your process has set a signal's disposition to SIG_IGN or SIG_DFL, then the signal is ignored (or default -- kill, core, or ignore) for all threads.If your process has set a signal's disposition to a specific handler routine, then you can control which thread will receive the signals by manipulating specific thread signal masks using pthread_sigmask(3).
You can nominate one thread to manage them all, or create one thread
per signal, or any mixture of these options for specific signals, or you
rely on the Linux kernel's current default behavior of delivering the
signal to the main thread.Some signals, however, are special:
|
沒有留言:
張貼留言