如何从过程中获取PID,而无需使用Java 9+的非法访问警告?

问题描述 投票:0回答:1
我需要在我开始的过程中获取基础OS PID。我现在正在使用的解决方案涉及通过使用类似代码的反射访问私有字段的访问:

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".

问题:是否有更好的方法(清洁,独立,保证不在Java的将来发行版)获得PID?这首先不应该被爪哇曝光吗?

java reflection process pid java-9
1个回答
7
投票
您可以利用Java9中引入的

Process#pid

,其中的样本将为:

ProcessBuilder pb = new ProcessBuilder("echo", "Hello World!"); Process p = pb.start(); System.out.printf("Process ID: %s%n", p.pid());
该方法的文档读取:

* Returns the native process ID of the process. * The native process ID is an identification number that the operating * system assigns to the process.
同样值得注意的是

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


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.