最近剛從linux C轉做android,老大突然看著我閒,叫我去驗證一下“一個進程有多個子線程,子線程都注冊監聽某個信號,另一個進程向它發送該信號的時候,它會怎麼處理?”。
帶著這個問題,我搜索了各個貼子之後,大概得出:
進程處理信號,你需要注冊signal的一個處理函數,線程你需要用signal_wait去等待一個信號。大體得出,如果一個多線程的進程得到了信號,它是會在它諸多子線程裡面選一個來執行,有人說是正在進行的那個線程。在多線程環境下,一般會讓其他子線程不處理信號,專門用一個線程來處理信號,把異步變成同步處理。
光看人家的貼子是不行的的。為此,我寫了如下代碼來驗證:
#include#include #include #include #include #include static pthread_t g_thread_ids[2]={0}; void ouch1(int sig) { printf("mainthread interrupted,thread id:%u\n",(unsigned int)pthread_self()); //signal(SIGINT,SIG_DFL); } void ouch2(int sig) { printf("child thread 1 interrupted,thread id:%u\n",(unsigned int)pthread_self()); //signal(SIGINT,SIG_DFL); } void ouch3(int sig) { printf("child thread 2 interrupted,thread id:%u\n",(unsigned int)pthread_self()); //signal(SIGINT,SIG_DFL); } void thread_loop1(char* msg) { printf("child thread 1 signal now \n"); signal(SIGINT,ouch2); printf("chilid thread1:%d,%s",(int)getpid(),msg); while(1); } void thread_loop2(char* msg) { printf("child thread 2 signal now\n"); signal(SIGINT,ouch3); printf("child thread2:%d,%s",(int)getpid(),msg); while(1); } void thread_wait2() { //waiting for thread terminate if(g_thread_ids[0]!=0) { pthread_join(g_thread_ids[0],NULL); printf("thread %d terminated\n",getpid()); } if(g_thread_ids[1]!=0) { pthread_join(g_thread_ids[1],NULL); printf("thread %d terminated\n",getpid()); } } //=============test multi-thread test. void start_test() { pthread_t thread1,thread2; char *msg1="this is thread 1\n"; char *msg2="this is thread 2\n"; printf("main thread signal now\n"); signal(SIGINT,ouch1); printf("main thread signal now\n"); pthread_create(&thread1,NULL,(void*)thread_loop1,(void*)msg1); g_thread_ids[0]=thread1; pthread_create(&thread2,NULL,(void*)thread_loop2,(void*)msg2); g_thread_ids[1]=thread2; thread_wait2(); printf("all thread finished its tasks\n"); return ; } int main() { start_test(); return 0; }
說明,跟正在執行的線程沒關系,指定一個之後就會一直由它來處理。如果對一個信號注冊了多次,那麼最後一次有效,其他的都無效。
mark一下。