以下這個小程式示範如何在 Linux 下開啟一條專門用來接收信號的執行緒。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
// 程式發生嚴重錯誤時輸出並結束
void error_quit(const char *str)
{
fprintf(stderr, "%s\n", str);
exit(1);
}
// 專門接收信號的執行緒
static void *sig_thread(void *arg)
{
printf("subthread tid: %u\n", (unsigned int)pthread_self());
sigset_t *set = (sigset_t *) arg;
int res, sig;
while (1)
{
// 掛起,等待信號到來
res = sigwait(set, &sig);
if (res != 0)
error_quit("sigwait error");
printf("tid: %u ", (unsigned int)pthread_self());
if (SIGALRM == sig)
{
printf("time out\n");
alarm(5); // 每 5 秒響一次
}
else if (SIGTSTP == sig)
{
printf("catch quit signal\n");
break;
}
else if (SIGINT == sig)
{
printf("quit program\n");
exit(0);
}
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t stid;
sigset_t set;
int res;
printf("main pid: %u, tid: %u\n",
(unsigned int)getpid(),
(unsigned int)pthread_self());
// 設定要由執行緒處理的信號集
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTSTP);
sigaddset(&set, SIGALRM);
// 在「所有」執行緒中先封鎖這些信號
res = pthread_sigmask(SIG_BLOCK, &set, NULL);
if (res != 0)
error_quit("pthread sigmask error");
alarm(1);
// 建立信號處理執行緒,主執行緒等它結束後才退出
res = pthread_create(&stid, NULL, &sig_thread, (void *) &set);
if (res != 0)
error_quit("pthread_create error");
pthread_join(stid, NULL);
printf("finish\n");
return 0;
}
這個模式在多執行緒程式中處理信號是公認的標準解法,關鍵在於 pthread_sigmask(SIG_BLOCK, ...) 的位置:它必須在建立任何執行緒之前(或在新執行緒建立時明確繼承遮罩)呼叫,因為新執行緒會繼承建立者的信號遮罩。先全域封鎖,再由專門的執行緒用 sigwait 同步等待,就能避免「到底是哪一條執行緒收到信號」這種不確定性。
若不做這層封鎖,Linux 的預設行為是「不特定執行緒」收到信號並跳入 handler,而 handler 在多執行緒環境中只能呼叫 async-signal-safe 的函式,稍一不慎就會造成死鎖。改用 sigwait 之後,信號被轉換成一個普通的回傳值,可以在執行緒中自由地做 printf、malloc 等一般運算,這是這個設計最大的好處。
程式中有兩處小問題。第一,sig_thread 宣告為回傳 void* 卻沒有 return,在部分編譯器下會產生警告,應補上 return NULL。第二,(unsigned int)pthread_self() 用來印執行緒 id 在概念上並不精確——pthread_t 在 Linux 上雖是 unsigned long,但標準並不保證它是整數型別,可攜的寫法應改用 printf("%lu", (unsigned long)pthread_self()) 或直接印 pthread_equal 的比較結果。
最後提醒,sigwait 是同步等待,因此 sig_thread 中的 alarm(5) 重新設定計時器是安全的;但若日後在該執行緒中加入其他阻塞型呼叫,要注意信號已被封鎖,某些依赖信號中斷的行為(例如 read 被 EINTR 打斷)就不會發生,這在設計上必須一致地看待。