最近刚从linux C转做android,老大突然看着我闲,叫我去验证一下“一个进程有多个子线程,子线程都注册监听某个信号,另一个进程向它发送该信号的时候,它会怎么处理?”。
带着这个问题,我搜索了各个贴子之后,大概得出:
进程处理信号,你需要注册signal的一个处理函数,线程你需要用signal_wait去等待一个信号。大体得出,如果一个多线程的进程得到了信号,它是会在它诸多子线程里面选一个来执行,有人说是正在进行的那个线程。在多线程环境下,一般会让其他子线程不处理信号,专门用一个线程来处理信号,把异步变成同步处理。
光看人家的贴子是不行的的。为此,我写了如下代码来验证:
#include <stdio.h>
#include <signal.h>
#include <stddef.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
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;
}
上述代码的输出是,谁最后调用signal,谁就会一直处理该信号。
说明,跟正在执行的线程没关系,指定一个之后就会一直由它来处理。如果对一个信号注册了多次,那么最后一次有效,其他的都无效。
mark一下。