嵌入式c语言判断线程是否存在

本文详细介绍了如何在C语言嵌入式环境中使用pthread_kill函数发送信号给线程,展示了SIGKILL、SIGQUIT和无效参数错误的情况,并分析了相应的返回值。
摘要由CSDN通过智能技术生成

嵌入式中常使用pthread_kill(pthread_t pthread)函数来判断,即pthread_kill(pthread, 0),向pthread线程传递一个信号,返回值为0,表示存在;ESRCH(3)表示信号不存在;EINVAL(22)表示无效参数

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <pthread.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h> 
 
int exit_flag = 0;
 
void sighandler(int signum)
{
   printf("capture signal number %d...\n", signum);
   if(SIGKILL == signum)
     exit(1);
}
 
void *threadfunc(void *parm)
{
	  int i = 0;
	  signal(SIGQUIT, sighandler);
	  while(1){
		  
		 printf("threadfunc i=%d\n",i++);
		 sleep(1);
		 if(exit_flag)
			 break;
	  }
	  printf("exit from hreadfunc\n");
	  return NULL;
}
 
void main()
{
	int rc = 0;
	pthread_t        threads;
    rc = pthread_kill(threads, 0);
	 
	printf("ESRCH=%d  EINVAL=%d\n",ESRCH,EINVAL); 
	printf("start rc=%d\n",rc);
    pthread_create(&threads, NULL, threadfunc, NULL);
	
	 sleep(1);
	 rc = pthread_kill(threads, 0);
	 printf("pthread_kill(threads, 0) rc=%d\n",rc);
	 sleep(5);
	  
	rc = pthread_kill(threads, SIGQUIT);
	sleep(1);
	printf("after SIGQUIT  rc=%d\n",rc);
	 
	exit_flag = 1;
	sleep(3);
	rc = pthread_kill(threads, 0);
	printf("after set exit_flag 1  rc=%d\n",rc);
	 
	 
	rc = pthread_kill(threads, SIGKILL);
	sleep(1);
	printf("after SIGKILL  rc=%d\n",rc); 
	 
	 
	while(1);
	return ;
}

测试结果:

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会C语言的男孩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值