收集系统中指定任务的所有线程

    有时候我们想对收集系统中某一些进程中的所有线程信息,这个时候写一个简单的脚本来实现。

    这里针对实际的例子进行讲解。

一 线程函数

    这里写来一个创建来三个线程的进程threadtest.c 。

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <stdarg.h>		/* asked by va_star and va_end */

pthread_t ntid1, ntid2, ntid3;
static int CHILD = 0;

void die(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	vfprintf(stderr, fmt, args);
	va_end(args);
	fflush(stdout);
	fflush(stderr);
	exit(1);
}

void * thr_fn1(void *arg) {
	printf("CHID%d,tid=%d\n", CHILD++, (int)(pthread_self()));
	while(1);
}
void * thr_fn2(void *arg) {
	printf("CHID%d,tid=%d\n", CHILD++, (int)(pthread_self()));
	while(1);
}
void * thr_fn3(void *arg) {
	printf("CHID%d,tid=%d\n", CHILD++, (int)(pthread_self()));
	while(1);
}

int main(int argc, char *argv[]) {
	int err;
	err = pthread_create(&ntid1, NULL, thr_fn1, NULL);
	if (err != 0) {
		die("can't create thread\n");
	}
	err = pthread_create(&ntid2, NULL, thr_fn2, NULL);
	if (err != 0) {
		die("can't create thread\n");
	}
	err = pthread_create(&ntid3, NULL, thr_fn3, NULL);
	if (err != 0) {
		die("can't create thread\n");
	}	
	while(1);
}

    上面的代码threadtest.c通过如下命令编译成可执行文件threadtest:
gcc -pthread -o threadtest threadtest.c

    然后复制两个此可执行文件即最终为:threadtest, threadtest1, threadtest_2, 然后运行这个三个可执行文件,通过ps -L查看这些3个任务及其线程的情况如下所示:

图1 三个进程及其子线程

二 线程收集的shell代码

    线程的手机主要通过shell脚本来搞定。整个流程很简单:1 先通过进程共有的名字找到进程的pid; 2 再通过这些pid找到各自线程的tids,然后将它们收集到一个文件中。

    这里还做了一点,将有下划线的进程给排除掉,用的是 grep -v test_ 来处理的,如下所示:

#!/bin/bash
datasets=$(ps | grep threadtest | grep -v test_ | awk '{print $1}')
for i in $datasets
do
        tidsets=$(ps -L | grep $i | awk '{print $2}')
        for j in $tidsets
        do
                 echo $j >> ./tids
        done
done


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值