Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, garanteed not to break in a future release of Java) to obtain the pid? Shouldn't this be exposed by Java in the first place?

like image 359
Olivier Gérardin Avatar asked Oct 24 '18 17:10

Olivier Gérardin


1 Answers

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
like image 97
Naman Avatar answered Nov 15 '22 21:11

Naman