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) –