#include <stdio.h>
#include <pthread.h>
#include <signal.h>
sigset_t set;
int sigint_signal = 0;
pthread_t monitor_thread, demo_thread;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *monitor()
{
while(1)
{
sigwait(&set, NULL);
pthread_mutex_lock(&m);
printf("__SIGINT received__\n");
sigint_signal = 1;
pthread_cancel(demo_thread);
pthread_mutex_unlock(&m);
}
}
void *demo_function(){
while(1){
pthread_mutex_lock(&m);
fprintf(stdout, "__Value of SIGNAL FLAG %d:__\n",sigint_signal);
pthread_mutex_unlock(&m);
}
return NULL;
}
int main(){
sigemptyset(&set);
sigaddset(&set,SIGINT);
pthread_sigmask(SIG_BLOCK,&set,0);
pthread_create(&monitor_thread, 0, monitor, NULL);
pthread_create(&demo_thread, 0, demo_function, NULL);
pthread_join(demo_thread, NULL);
return 0;
}
monitor_thread
是連續運行趕上SIGINT
信號線。接收到信號後,它必須取消另一個線程並結束。 SIGINT是越來越接收,這可以與可變sigint_signal
成爲1
一旦信號是received.But pthread_cancel
是沒有得到執行,因爲一旦sigint_signal
的值改變爲1
,所述demo_thread
繼續運行的值進行驗證。請幫忙。無法趕上SIGINT信號在多線程程序
我用來編譯的命令是'gcc -g -Wall filename -o executable -lpthread'。 – 2015-02-08 05:07:25
你真的不應該依賴'pthread_cancel'。您應該讓線程函數中的循環讀取由信號處理程序分配的變量,並在設置該變量時自行終止。 – 2015-02-08 05:11:22
感謝@JohnZwinck,這個建議可行,但只是想問爲什麼不依靠pthread_cancel。 – 2015-02-08 05:23:50