判断线程是否存活——pthread_kill()函数

一、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;

}

运行结果:
在这里插入图片描述

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值