Dave Jackson
Dave Jackson

Reputation: 837

How to get pid from binary which the run via getRuntime().exec

How to get pid from binary which the run via getRuntime().exec. I want to get pid from /data/data/com.tes.tes/binary

My code to run the service is:

MyExecShell("/data/data/com.tes.tes/binary");

public void MyExecShell(String cmd) {
    Process p = null;
    try {
        p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
    } catch (Exception e) {
        // TODO: handle exception
    }
}

If I run command ps | grep binary I get result:

app_96    12468 1     1176   680   c0194d70 0007efb4 S /data/data/com.tes.tes/binary

I want to get the pid, how to do it? I have tried with this:

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> list = manager.getRunningAppProcesses();
        if (list != null) {
            for (int i = 0; i < list.size(); ++i) {
                Log.d("DLOG", list.get(i).toString() + "\n");
                if ("/data/data/com.tes.tes/binary"
                        .matches(list.get(i).toString())) {
                    int pid = android.os.Process.getUidForName("/data/data/com.tes.tes/binary");
                    Log.d("DLOG","PID: "+pid);
                }
            }
        }

But not success.

Thanks.

Upvotes: 0

Views: 321

Answers (1)

flx
flx

Reputation: 14226

The problem is, that the running process is not an app context. You can try to fetch the pid by standard Linux methods:

private int getPid() {
    int pid = -1;
    Process p = null;
    try {
        p = Runtime.getRuntime().exec("ps");
        p.waitFor();
        InputStream is = p.getInputStream();
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        String s;
        while ((s=r.readLine())!= null) {
            if (s.contains("/data/data/com.tes.tes/binary")) {
                // TODO get pid from ps output
                // like " | awk '{ pring $2 }'
                // pid = something;
            }
        }
        r.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
    return pid;
}

Upvotes: 2

Related Questions