Jishnu Banerjee Jishnu Banerjee - 3 months ago 10
Linux Question

Why child threads alive after the main threads are killed?

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.


  1. I'm receiving the signal from the child thread. Why is it printing the
    threadID
    of the parent thread?

  2. 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???

Answer

Signals are delivered to the process, not to individual threads. So, you can't have a signal handler just for one thread as you are doing here. What you can do is block signals you are interested in using pthread_sigmask() and let a dedicated thread handle signals using sigwait(), which is the most common way.

Comments