get_pid_by_name

Linux 通过名字获得一个thread 的Pid,/proc中保存的所有thread的信息,可以通过ls看到,各个进程的目录以PID命名,/proc/PID/stat 文件记录了thread的信息,通过遍历这个文件,就可以通过名字找到对应的PID。stat文件中的内容:
cat stat
1400 (rild) S 1 1400 0 0 -1 4194560 288 9108 3 2 10 15 10 194 20 0 3 0 785 4673536 167 4294967295 32768 37204 3198446656 3198445164 4294903072 0 0 0 3
8120 4294967295 0 0 17 0 0 0 0 0 0

 

 

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>

#include <string.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>

#include <pwd.h>

#include <cutils/sched_policy.h>
#define isdigit(a) ((unsigned)((a) - '0') <= 9)

static char *nexttoksep(char **strp, char *sep)
{
    char *p = strsep(strp,sep);
    return (p == 0) ? "" : p;
}
static char *nexttok(char **strp)
{
    return nexttoksep(strp, " ");
}


static int ps_line(int pidloop,char *namefilter)
{
    char statline[1024];
    int fd, r,pid;
    char *ptr, *name;

    sprintf(statline, "/proc/%d/stat", pidloop);
    fd = open(statline, O_RDONLY);
    if(fd == 0) return -1;
    r = read(fd, statline, 1023);
    close(fd);
    if(r < 0) return -1;
    statline[r] = 0;

    ptr = statline;
    nexttok(&ptr); // skip pid
    ptr++;          // skip "("

    name = ptr;
    ptr = strrchr(ptr, ')'); // Skip to *last* occurence of ')',
    *ptr++ = '\0';           // and null-terminate name.

    if(!namefilter || !strncmp(name, namefilter, strlen(namefilter))) 
	{	
		pid = pidloop;
		return pid;
    }
	else
    	return 0;
}
int get_pid_by_name(char *name)
{
    DIR *d;
    struct dirent *de;
    char *namefilter = 0;
	int pidloop = 0;
	int pid = 0;
    
    d = opendir("/proc");
    if(d == 0) return -1;
	namefilter = name;
    while(((de = readdir(d)) != 0)&&(pid == 0) ){
        if(isdigit(de->d_name[0])){
            pidloop = atoi(de->d_name);
            pid = ps_line(pidloop,namefilter);
        }
    }
    closedir(d);
    return pid;
}


 

 

参考代码:busybox:find_pid_by_name.c

Android:system\core\toolbox\ps.c

 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值