I think out two method to resolve this question but they can’t reach the expectation .
I use the ‘Process’ to exec “ps -ef”
I can through this method to get all lines and I can filter them by my running command.But If I have many same command process.This isn’t work.
I use the JNA to get PID
Field field = null; Integer pid = -1; try { Class clazz = Class.forName("java.lang.UNIXProcess"); field = clazz.getDeclaredField("pid"); field.setAccessible(true); pid = (Integer) field.get(process); } catch (Throwable e) { e.printStackTrace(); }
This way only can get the PID of running window. It isn’t the true PID of process.
what should I do?
Thanks!
Advertisement
Answer
Java 9
Java 9 introduces a number “nice” changes, one is the inclusion of the native PID of a Process
– see Process#pid
for more details
import java.io.IOException; import java.io.InputStream; public class Test { public static void main(String[] args) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("/Applications/Xcode.app/Contents/MacOS/Xcode"); pb.redirectErrorStream(true); Process p = pb.start(); // Yes, I'm a bad developer, but I just want to demonstrate // the use of the PID method :/ new Thread(new Consumer(p.getInputStream())).start(); System.out.println("PID = " + p.pid()); p.waitFor(); System.out.println("Exit with " + p.exitValue()); } public static class Consumer implements Runnable { private InputStream is; public Consumer(InputStream is) { this.is = is; } @Override public void run() { try { int value = -1; while ((value = is.read()) != -1) { // I'm ignoring it for brevity } } catch (IOException ex) { ex.printStackTrace(); } } } }
You can also obtain a reference to the ProcessHandle
for the Process
via the Process#toHandle
method, which is kind of nice