gpt4 book ai didi

java - ProcessHandle onExit 有空数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:27:49 25 4
gpt4 key购买 nike

我目前正在测试来自 java 9 的 Process API,但我在使用以下代码时遇到了一些问题:

Process process = new ProcessBuilder( List.of("ping", "-i", "1", "-c", "4", "google.com")).start();

CompletableFuture<Void> startTimeFuture = process.toHandle().onExit()
.thenApply(ProcessHandle::info)
.thenApply(ProcessHandle.Info::startInstant)
.thenAccept(System.out::println);

startTimeFuture.get();

当我执行这个片段时,我在终端中得到 Optional.empty。Javadoc 声明 info 方法返回可用的任何数据,因此我怀疑 JVM 无法获取有关衍生进程的信息。但是,当我将来尝试从 ProcessHandle 获取 pid 时,我会得到适当的值。

总结一下,我的问题:

调用onExit()后,有什么方法可以得到非空的ProcessHandle.Info吗?

我正在使用 Ubuntu 16.04 LTS

编辑 - 这是我执行 ping -i 1 -c 5 google.com

时终端的输出

PING google.com (xxx.xxx.16.46) 56(84) bytes of data.

64 bytes from waw02s14-in-f14.1e100.net (xxx.xxx.16.46): icmp_seq=1 ttl=52 time=6.71 ms

64 bytes from waw02s14-in-f14.1e100.net (xxx.xxx.16.46): icmp_seq=2 ttl=52 time=6.26 ms

64 bytes from waw02s14-in-f14.1e100.net (xxx.xxx.16.46): icmp_seq=3 ttl=52 time=16.6 ms

64 bytes from waw02s14-in-f14.1e100.net (xxx.xxx.16.46): icmp_seq=4 ttl=52 time=10.6 ms

64 bytes from waw02s14-in-f14.1e100.net (xxx.xxx.16.46): icmp_seq=5 ttl=52 time=13.4 ms

--- google.com ping statistics ---

5 packets transmitted, 5 received, 0% packet loss, time 4007ms rtt min/avg/max/mdev = 6.267/10.746/16.667/3.968 ms

更新的用例:- 我想检查是否可以,给定命令执行了多少时间,例如通过调用 ProcessHandle.Info::totalCpuDuration

最佳答案

我想我找到了这种行为的原因(至少在 Linux 发行版上)。

ProcessHandle.Info 对象使用以下方法创建:

public static ProcessHandle.Info info(long pid, long startTime) {
Info info = new Info();
info.info0(pid);
if (startTime != info.startTime) {
info.command = null;
info.arguments = null;
info.startTime = -1L;
info.totalTime = -1L;
info.user = null;
}
return info;
}

其中 info.info0(pid) 是对本地方法的调用。所以我下载了openjdk源代码并检查了这个方法的实现。在 linux 上,JVM 通过读取 /proc/{pid}/stat/proc/{pid}/cmdline/proc/{pid}/来检索进程数据exe 在进程终止后不再可用。

回答我的问题:

无法获取已完成进程的 ProcessHandle.Info

关于java - ProcessHandle onExit 有空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49159686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com