如何通过getRuntime()。exec从二进制文件获取pid

时间:2013-10-07 08:42:43

标签: android

如何通过getRuntime()。exec从二进制文件获取pid。 我希望从/data/data/com.tes.tes/binary

获得pid

我运行服务的代码是:

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

但不成功。

感谢。

1 个答案:

答案 0 :(得分: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;
}