java - 如何使用 Java 9+ 从 Process 获取 pid 而没有非法访问警告?
问题描述
我需要为我启动的进程获取底层操作系统 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;
}
它有效,但这种方法存在几个问题,一个是您需要在 Windows 上做额外的工作,因为 Windows 特定的 Process 子类不存储“pid”字段而是“handle”字段(所以你需要做一点 JNA 来获取实际的 pid),另一个是从 Java 9 开始它会触发一堆可怕的警告,比如“警告:发生了非法反射访问操作”。
所以问题是:有没有更好的方法(干净,独立于操作系统,保证在未来的 Java 版本中不会中断)来获取 pid?这不应该首先由 Java 公开吗?
解决方案
您可以使用Process#pid
Java9 中引入的,示例如下:
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
推荐阅读
- javascript - 使用 Slick Carousel 同步图像
- javascript - 如何使我的图像从旋转到直(HTML,CSS,JS,)
- vba - MS Access:将数据验证规则复制/粘贴到多个字段?
- javascript - 类型“void”Angular 9 上不存在属性“管道”
- c# - 加了几个小数后,再给HashSet加一个大数:会发生什么?
- ssl - 什么是 serverAuth 和 clientAuth?
- javascript - 如何通过更改 HTML 站点中的 CSS 来连续显示选定的按钮?
- c# - 如何在 C# 中将永久数据添加到 GridView
- python - 通过`firebase`和`gcloud`启动firestore模拟器的区别?
- docker - 访问docker容器内的私有IP