1
这里是我的代码:POSIX多线程和信号配置
void handler(int sig)
{
printf("%lu recv signal\n", pthread_self());
}
void* thread_fun(void *threadid)
{
printf("thread %lu created\n", pthread_self());
while(1){
sleep(1);
}
return NULL;
}
int main(void)
{
struct sigaction act;
act.sa_handler = handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, NULL);
printf("thread %lu created\n", pthread_self());
pthread_t t1,t2;
pthread_create(&t1, NULL, thread_fun, NULL);
pthread_create(&t2, NULL, thread_fun, NULL);
while(1)
sleep(1);
return 0;
}
APUE表明,在多线程处理,信号像SIGINT将被输送到一个随机的线程,但是,当我运行在Ubuntu这个代码14.04,似乎信号总是传递给主线程。有谁知道有什么问题?
正式的,你不应该在信号处理程序中调用'printf()'。请参阅[如何避免在信号处理程序中调用'printf()'](http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler/16891799# 16891799) –