0

如何从通过 getRuntime().exec 运行的二进制文件中获取 pid。我想从/data/data/com.tes.tes/binary

我运行该服务的代码是:

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

如果我运行命令ps | grep binary,我会得到结果:

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

我想得到pid,怎么办?我试过这个:

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

但不是成功。

谢谢。

4

1 回答 1

2

问题是,正在运行的进程不是应用程序上下文。您可以尝试通过标准 Linux 方法获取 pid:

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;
}
于 2013-10-07T09:20:08.647 回答