I have written a code where I have created two child threads from the parent thread.
Then, with receiving a signal from another terminal inside those child threads, I printed the threadID
and exited the thread.
I have 2 questions.
I'm receiving the signal from the child thread. Why is it printing the
threadID
of the parent thread?After killing the parent thread, how can be the child threads alive??
The Code :
void sig_handler(int signo)
{
if (signo == 1){
printf("%d\n", pthread_self());
pthread_exit(NULL);
}
}
void* doSomeThing(void* arg)
{
printf("In function -> %d\n", pthread_self());
if (signal(1, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGHUP\n");
while(1)
sleep(1);
return NULL;
}
int main(int argc, char *argv[])
{
printf("In function -> %d\n", pthread_self());
char *ch1;
pthread_t tid1, tid2;
ch1 = "random";
int ret1, ret2;
ret1 = pthread_create(&tid1, NULL, &doSomeThing, (void *) ch1 );
ret2 = pthread_create(&tid2, NULL, &doSomeThing, (void *) ch1 );
while(1)
sleep(1);
return 0;
}
Here is the image of the output given in terminal :
The first 3 lines are the 3 threadID
s. 1st one is the Main threadID
s, then the two secondary threads.
Then the threadID
s printed from the following block of code.
if (signo == 1){
printf("%d\n", pthread_self());
pthread_exit(NULL);
}
Why is this happening???
signal
doesn't really work with threads. – Kerrek SBpthread_self()
function is not giving the properthreadID
?? As it is called after receiving thesignal
?? – jbsu32pthread_self()
will give the thread id of the calling thread. But the real issue is that it's not possible to have per-thread signal handlers; signal handling is process wide. See an example in the linked man page on how to block signals. – P.Psignal
] in a multi-threaded program results in undefined behaviour." – Kerrek SB