根据进程名获取PID

来自个人维基
跳转至: 导航搜索
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/time.h>
#include<sys/resource.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

#include <utils/Log.h>

#include <dirent.h>
#include <ctype.h> 

/*===start:for system_server monitor===*/
int findPidByName( char* pidName)
{
#define READ_BUF_SIZE (256)
    DIR *dir;
    struct dirent *next;
    int pid = 0;
    int i=0;
 
        ///proc中包括当前的进程信息,读取该目录
    dir = opendir("/proc");
    if (!dir)
        LOGE("vivo_daemon,Cannot open /proc");
     
    //遍历
    while ((next = readdir(dir)) != NULL) {
        FILE *status;
        char filename[READ_BUF_SIZE];
        char buffer[READ_BUF_SIZE];
        char name[READ_BUF_SIZE];
 
        /* Must skip ".." since that is outside /proc */
        if (strcmp(next->d_name, "..") == 0)
            continue;
 
        /* If it isn't a number, we don't want it */
        if (!isdigit(*next->d_name))
            continue;
        //设置进程
        sprintf(filename, "/proc/%s/status", next->d_name);
        if (! (status = fopen(filename, "r")) ) {
            continue;
        }
        if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL) {
            fclose(status);
            continue;
        }
        fclose(status);
 
        //得到进程id
        /* Buffer should contain a string like "Name:   binary_name" */
        sscanf(buffer, "%*s %s", name);
        if (strcmp(name, pidName) == 0) {
            //pidList=(long*)realloc( pidList, sizeof(long) * (i+2));
            //pidList[i++]=strtol(next->d_name, NULL, 0);
            pid = strtol(next->d_name, NULL, 0);
            break;
        }
    }

    return pid;
}

此函数摘自 http://kb.cnblogs.com/a/2360817/ ,不过为了使用更加方便有些许更改,主要是去掉了对同一进程名有多个pid的支持,改为获取到第一个pid则立刻返回,这样改的原因是android在很多状况下其进程都是惟一的,这样更改后搜索速度有所提升,且也更加易用!