android获取进程pid的方法,android通过进程名查找PID

该代码段展示了一个在Linux系统下通过遍历/proc目录获取进程PID及其对应命令行名称的函数。它首先打开/proc目录,然后读取每个以数字开头的条目(代表进程ID)。接着,它读取对应的stat和cmdline文件,从中提取进程名并进行比较,如果找到匹配的进程名,则返回其PID。这个函数对于监控或管理系统进程非常有用。
摘要由CSDN通过智能技术生成

int find_pid(char * process_name){

DIR *d;

struct dirent *de;

ssize_t readcount;

char tmp[256];

char tmp_name[256];

char pro_name[256];

char buffer[MAX_READ];

char name_buffer[256];

int pid;

int tmp_pid;

int fd,fd2;

if((d = opendir("/proc")) == 0)

return -1;

while((de = readdir(d)) != 0){

if(isdigit(de->d_name[0])){

pid = atoi(de->d_name);

sprintf(tmp,"/proc/%d/stat",pid);

sprintf(tmp_name,"/proc/%d/cmdline",pid);

fd = open(tmp,O_RDONLY);

if(fd == -1)

return -1;

readcount = read(fd, (void*)buffer, MAX_READ);

if(readcount == -1)

return -1;

close(fd);

fd2 = open(tmp_name,O_RDONLY);

if(fd2 == -1)

return -1;

readcount = read(fd2,(void*)name_buffer, 256);

if(readcount == -1)

return -1;

name_buffer[readcount] = '\0';

close(fd2);

if(name_buffer[0]){//in default, the full process name is keep in /proc/PID/cmdline

if(!strcmp(name_buffer,process_name) || strstr(name_buffer,process_name) != NULL){

strcpy(full_proname,name_buffer);

return pid;

}

}

sscanf(buffer,"%d%*[^(](%[^)]",&tmp_pid,pro_name);

if(tmp_pid != pid)

return -1;

if(!strcmp(pro_name,process_name) || strstr(pro_name,process_name) != NULL){

return pid;

}else{

if(strlen(pro_name) == MAX_PROCESSNAME_INFILE && strlen(process_name) >= MAX_PROCESSNAME_INFILE)//the max length in stat/status of the [process name] value.

if(strstr(process_name,pro_name) != NULL)

return pid;

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值