码迷,mamicode.com
首页 > 编程语言 > 详细

linux查看线程是否存活

时间:2015-11-19 10:57:02      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

pthread_kill(),向指定ID的线程发送一个信号,如果线程不处理该信号,则按照信号默认的行为作用于整个进程。信号值0为保留信号,作用是根据函数的返回值判断线程是不是还活着。

pthread_kill的返回值:
成功:0
线程不存在:ESRCH
信号不合法:EINVAL

a.cpp:

/*************************************************************************
    * File: a.cpp
    * Brief: 
    * Created Time: Wed 18 Nov 2015 04:43:51 PM PST
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<signal.h>
#include<errno.h>
#include<iostream>
using namespace std;


void* thread_fun(void*)
{
    int i=0;
    for(;i<10;i++)
        sleep(1);

    //int a=0;
    //int b=3/a;

    printf("thead exit\n");
    pthread_exit((void *)0);
}

void check(pthread_t tid)
{
    static int seq=1;
    int ret=pthread_kill(tid,0);
    if(ESRCH==ret)
        printf("%02d. ID为0x%x的线程不存在或者已经退出。\n",seq++,(unsigned int)tid);
    else if(EINVAL==ret)
        printf("%02d. 发送信号非法。\n",seq++);
    else
        printf("%02d. ID为0x%x的线程目前仍然存活。\n",seq++,(unsigned int)tid);
}

int main()
{
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    pthread_create(&tid,&attr,thread_fun,NULL);

    int i=0;
    for(;i<15;i++)
    {
        check(tid);
        sleep(1);
    }
    printf("done\n");
    return 0;
}

 

Makefile:

all: a.cpp
    g++ a.cpp -o a.out -lpthread

clean:
    rm -rf a.out

 

编译运行效果如下:

技术分享

linux查看线程是否存活

标签:

原文地址:http://www.cnblogs.com/liyou-blog/p/4976628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!