Search code examples
javareflectionprocesspidjava-9

How to obtain pid from Process without illegal access warning with Java 9+?


I need to obtain the underlying OS PID for a Process I start. The solution I'm using now involves access to a private field through reflection using code like this:

private long getLongField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException {
    Field field = target.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    long value = field.getLong(target);
    field.setAccessible(false);
    return value;
}

It works but there are several problems with this approach, one being that you need to do extra work on Windows because the Windows-specific Process subclass doesn't store a "pid" field but a "handle" field (so you need to do a bit of JNA to get the actual pid), and another being that starting with Java 9 it triggers a bunch of scary warnings like "WARNING: An illegal reflective access operation has occurred".

So the question: is there a better way (clean, OS independent, guaranteed not to break in a future release of Java) to obtain the pid? Shouldn't this be exposed by Java in the first place?


Solution

  • You can make use of the Process#pid introduced in Java9, a sample of that would be as:

    ProcessBuilder pb = new ProcessBuilder("echo", "Hello World!");
    Process p = pb.start();
    System.out.printf("Process ID: %s%n", p.pid());
    

    The documentation of the method reads:

    * Returns the native process ID of the process.
    * The native process ID is an identification number that the operating
    * system assigns to the process.
    

    and noteworthy as well from the same

    * @throws UnsupportedOperationException if the Process implementation
    *         does not support this operation