【发布时间】:2016-08-09 16:18:25
【问题描述】:
我尝试在下面的代码中为子线程安装 SIGINT 处理程序。我希望子线程在从父进程接收到 SIGINT 时打印 hello 。但是,什么都没有出来,程序立即退出。
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
typedef struct proxy_node_t{
pthread_t sub_thread;
pthread_t p_self;
}proxy_node;
proxy_node* proxy;
static void proxy_singnal_handler(){
printf("Hello\n");
return;
}
static void* t_consensus(void *arg){
signal(SIGINT,proxy_singnal_handler);
sleep(1);
return NULL;
}
int main(int argc, char **argv)
{
proxy = (proxy_node*)malloc(sizeof(proxy_node));
proxy->p_self = pthread_self();
pthread_create(&proxy->sub_thread,NULL,t_consensus,NULL);
pthread_kill(proxy->sub_thread,SIGINT);
sleep(1);
return 0;
}
【问题讨论】:
-
printf()不是异步安全的。您不能从信号处理程序中调用它。此外,在创建的线程调用signal()和主线程调用pthread_kill()之间存在竞争。
标签: c multithreading pthreads signals