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