android通过进程名查找PID

[申明]原创内容,转载请申明!

需要通过(部分)进程名查找PID,然后可以kill指定的进程了.

读取/proc/PID/cmdline    为完整进程名,即PS命令可以看到的进程名.
读取/proc/PID/stat           为进程各种信息.包括PID,部分进程名(不超过15字节),以及其他一些信息.

以下是主体部分.



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;
			}

			
		}
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值