對於pthread_kill的一些誤解

今天在寫代碼的時候,想通過pthread_kill接口殺死一個線程,因爲之前學習《Linux/Unix系統編程手冊》的時候,裏面對於該接口的功能介紹是如下:

函數pthread_kill()向同一進程下的另一線程發送信號。因爲僅在同一進程中可保證線程ID的唯一性,所以無法調用pthread_kill向其他進程中的線程發送信號。

所以就感覺pthread_kill與kill差不多,不過一個是向線程發送,一個是向進程發送,但是在使用中,與設想的完全不一樣。上測試代碼:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void *func(void *argv)
{
    while (1) {
        printf("I am thread, %ld\n", pthread_self());
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t t;
    pthread_create(&t, NULL, func, NULL);
    sleep(10);
    printf("send kill to thread\n");
    pthread_kill(t, SIGKILL);
    sleep(10);
    printf("end\n");
}

代碼很簡單,就是創建一個線程,一直打印信息,然後過10s,主線程殺死子線程,然後再過10s退出。理想中的運行狀態就是子線程運行10s,然後被主線程殺死,再過10s,主線程退出。但是實際上,最終的結果是,10s後,pthread_kill直接把主線程給殺死了,根本不會運行最後的10s睡眠和打印。後來還嘗試了SIGTERM信號,結果是一樣的。

對這個結果感到很意外,於是只能去查了man手冊,man手冊的解釋如下:

    Signal dispositions are process-wide: if a signal handler is installed, the handler will be invoked in the thread thread, but if the disposition of the signal is "stop", "continue", or "terminate", this action will affect the whole process.

可以看到,在man手冊中清楚的說明了,如果信號是“stop”, “continue”或者“terminate”這種類型的信號,那麼將會影響整個進程,所以整個進程都被殺掉了。

其實爲了達到之前的目的,可以使用pthread_cancel函數,直接向指定線程發送取消請求就可以了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章