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

raf picture raf · Jan 20, 2011 · Viewed 113.5k times · Source

I've started a process with following code

 ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
 try {
     Process p = pb.start();       
 } 
 catch (IOException ex) {}

Now I need to know the process's pid that I've just started.

Answer

czerny picture czerny · Feb 8, 2017

Since Java 9 class Process has new method long pid(), so it is as simple as

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
try {
    Process p = pb.start();
    long pid = p.pid();      
} catch (IOException ex) {
    // ...
}