Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android runtime.getruntime().exec() get process id

How do I get the process id of a process started using runtime.getruntime().exec() via an android application??

Here is the problem.. I start a process using runtime.getruntime().exec() from my UI APP. If my android UI app is still running, i can use destroy to kill the process.. But say i exit the app using home or back button and when i reopen the ui app, process object is null. So then i would need the PID of the process to kill it.

is there a better way to do this?

like image 450
Hari Avatar asked Oct 24 '12 18:10

Hari


Video Answer


2 Answers

Android java.lang.Process implementation is java.lang.ProcessManager$ProcessImpl and it has field private final int pid;. It can be get from Reflection:

public static int getPid(Process p) {
    int pid = -1;

    try {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = f.getInt(p);
        f.setAccessible(false);
    } catch (Throwable e) {
        pid = -1;
    }
    return pid;
}

Another way - use toString:

    public String toString() {
        return "Process[pid=" + pid + "]";
    }

You can parse output and get pid without Reflection.

So full method:

public static int getPid(Process p) {
    int pid = -1;

    try {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = f.getInt(p);
        f.setAccessible(false);
    } catch (Throwable ignored) {
        try {
            Matcher m = Pattern.compile("pid=(\\d+)").matcher(p.toString());
            pid = m.find() ? Integer.parseInt(m.group(1)) : -1;
        } catch (Throwable ignored2) {
            pid = -1;
        }
    }
    return pid;
}
like image 165
Enyby Avatar answered Sep 23 '22 17:09

Enyby


Will you be using the PID to kill the process? If so, you can simply call destroy() on your Process instance. No need for the PID. Please note that you will need to launch the process using ProcessBuilder, rather than getRuntime().exec(), for this to work.

If you really do need the process ID, you may need to use a shell script. There is no way to get the PID from Java, AFAIK.

EDIT:

Since you need to keep a handle on the Process after leaving your app and returning to it, one solution is to make a static member in the class that spawns the Process:

private static Process myProcess;

Use this member to store the Process that you get back from calling start() on your ProcessBuilder. The static member will stay around as long as your app is in memory — it doesn't have to be visible. It should be possible to kill the process after returning to your app. If the system happens to kill your app to free up resources, then you will have no way to terminate the child process (if it stays running), but this solution should work for most cases.

like image 28
acj Avatar answered Sep 22 '22 17:09

acj