xxking
xxking

Reputation: 79

NDK get pid from package name

I want create a function but I don't know how to get the PID of the app.

in java code

     public static intgetPID(String packageName) {
       //do something
      }

     //how do this NDK
    int getPid(string packagename)
   {
      //C++ code  
      //  how to finish
   }

Upvotes: 2

Views: 2102

Answers (1)

xxking
xxking

Reputation: 79

read /proc/self/status parse string to get pid

int find_pid_of(const char *process_name)
{
    int id;
    pid_t pid = -1;
    DIR* dir;
    FILE *fp;
    char filename[32];
    char cmdline[256];

    struct dirent * entry;

    if (process_name == NULL)
        return -1;

    dir = opendir("/proc");
    if (dir == NULL)
        return -1;

    while((entry = readdir(dir)) != NULL) {
        id = atoi(entry->d_name);
        if (id != 0) {
            sprintf(filename, "/proc/%d/cmdline", id);
            fp = fopen(filename, "r");
            if (fp) {
                fgets(cmdline, sizeof(cmdline), fp);
                fclose(fp);

                if (strcmp(process_name, cmdline) == 0) {
                    /* process found */
                    pid = id;
                    break;
                }
            }
        }
    }

    closedir(dir);
    return pid;
}

Upvotes: 1

Related Questions