一、pthread_kill()函数介绍
1.函数作用
1>pthread_kill()函数的作用是向某个线程传递一个信号
2>[注意]创建的线程中使用signal(SIGKILL,sig_handler)函数去处理对应的信号,如果你给一个线程发送了SIGQUIT,
但线程却没有实现signal处理函数,则整个进程退出
信号的设置:signal函数
2.函数原型
#include <pthread.h>
#include<signal.h>
int pthread_kill(pthread_t thread, int sig);
参数:参数1:线程id 参数2:要发送给线程的信号
返回值:成功:0 线程不存在:ESRCH 信号不合法:EINVAL
3.判断线程是否存在
当我们给线程发送一个0就可以判断线程是否存在pthread_kill(tid, 0);
程序demon
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
int thread_id1,thread_id2;
void *function1(void *arg)
{
thread_id1=pthread_self();
printf("start thread1 id = %x \n",thread_id1);
return;
}
void *function2(void *arg)
{
thread_id2=pthread_self();
printf("start thread2 id = %x \n",thread_id2);
sleep(3);
return;
}
int main()
{
pthread_t tid1,tid2;
if(-1==pthread_create(&tid1,NULL,function1,NULL))
printf("tid1 create fail\n");
else
pthread_detach(tid1);
if(-1==pthread_create(&tid2,NULL,function2,NULL))
printf("tid1 create fail\n");
else
pthread_detach(tid2);
sleep(1);
int kill_ret1 = pthread_kill(tid1,0);
if(kill_ret1 ==ESRCH)
{
printf("线程1不存在 id = %x \n",thread_id1);
}else if(kill_ret1 == 0){
printf("线程1存活 id = %x \n",thread_id1);
}
int kill_ret2 = pthread_kill(tid2,0);
if(kill_ret2 == ESRCH)
{
printf("线程2不存在 id = %x \n",thread_id2);
}else if(kill_ret2 == 0){
printf("线程2存活 id = %x \n",thread_id2);
}
sleep(2);
return 0;
}
运行结果: