Stack Overflow archive
5 score

How to get PID of process I've just started within java program?

score
5
question views
145.2K
license
CC BY-SA 3.0

In my testing all IMPL classes had the field "pid". This has worked for me:

java
public static int getPid(Process process) {
    try {
        Class<?> cProcessImpl = process.getClass();
        Field fPid = cProcessImpl.getDeclaredField("pid");
        if (!fPid.isAccessible()) {
            fPid.setAccessible(true);
        }
        return fPid.getInt(process);
    } catch (Exception e) {
        return -1;
    }
}

Just make sure the returned value is not -1. If it is, then parse the output of ps.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.