Reputation: 63
Here is my code:
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 indicated that in a multithreading process, signal like SIGINT will be delivered into a random thread, but, when I run this code on Ubuntu 14.04, it seems that signal is always delivered to the main thread. Does anyone know what's the problem?
Upvotes: 1
Views: 110
Reputation: 36391
"Random thread" doesn't means that it is delivered to a thread chosen at random, but that it can be delivered to any thread the implementers want. So random choice is a possibility, but any other choice is possible. On your system the choice is: the main thread first if possible.
You may read the OpenGroup Signal Concepts document. There is no "random" choice. It is said that among all threads one will be chosen that does not block the signal or is waiting for the signal.
So the only thing you should take in account is that possibly any thread can receive the signal.
Upvotes: 3