【发布时间】:2016-08-03 08:46:20
【问题描述】:
我编写了一个代码,我从父线程创建了两个子线程。
然后,在这些子线程中接收到来自另一个终端的信号后,我打印了threadID 并退出了线程。
我有 2 个问题。
我正在接收来自子线程的信号。为什么打印父线程的
threadID?杀死父线程后,子线程怎么可能还活着??
代码:
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;
}
这是终端中给出的输出图像:
前 3 行是 3 个threadIDs。第一个是主线程threadIDs,然后是两个辅助线程。
然后从下面的代码块中打印出threadIDs。
if (signo == 1){
printf("%d\n", pthread_self());
pthread_exit(NULL);
}
为什么会这样???
【问题讨论】:
-
signal不适用于线程。 -
这是否意味着
pthread_self()函数没有给出正确的threadID?在收到signal?? 后调用 -
@JishnuBanerjee
pthread_self()将给出调用线程的线程 ID。但真正的问题是不可能有每个线程的信号处理程序。信号处理是全过程的。请参阅链接的手册页中有关如何阻止信号的示例。 -
C 标准说:“在多线程程序中使用这个函数 [
signal] 会导致未定义的行为。”
标签: c linux multithreading pthreads signals