ProcessHandle onExit具有空数据

时间:2018-03-07 19:18:50

标签: java java-9 processhandle

我目前正在测试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时,我会得到适当的价值。

总结一下,我的问题是:

调用ProcessHandle.Info后,有没有办法让非空onExit()

我正在使用Ubuntu 16.04 LTS

编辑 - 执行ping -i 1 -c 5 google.com时,这是终端的输出

  

PING google.com(xxx.xxx.16.46)56(84)字节的数据。

     

来自waw02s14-in-f14.1e100.net(xxx.xxx.16.46)的64个字节:icmp_seq = 1 ttl = 52 time = 6.71 ms

     

来自waw02s14-in-f14.1e100.net(xxx.xxx.16.46)的64个字节:icmp_seq = 2 ttl = 52 time = 6.26 ms

     

64字节来自waw02s14-in-f14.1e100.net(xxx.xxx.16.46):icmp_seq = 3 ttl = 52 time = 16.6 ms

     来自waw02s14-in-f14.1e100.net(xxx.xxx.16.46)的

64个字节:icmp_seq = 4 ttl = 52 time = 10.6 ms

     

来自waw02s14-in-f14.1e100.net(xxx.xxx.16.46)的64个字节:icmp_seq = 5 ttl = 52 time = 13.4 ms

     

--- google.com ping statistics ---

     发送5个包,5个接收,0%丢包,时间4007ms   rtt min / avg / max / mdev = 6.267 / 10.746 / 16.667 / 3.968 ms

更新了用例 : - 我想检查一下命令执行的时间,例如调用 { {3}}

1 个答案:

答案 0 :(得分:2)

我认为我找到了这种行为的原因(至少在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完成的流程。