Java9 进程API详细介绍(3)

main()方法中调用allProcesses()方法,从路径名显示地将线程句柄流链式导入到一个filter之后再包装到一个新的线程句柄流。 (在我的环境中,当进程终止之后就不会打印出路径) limit(4) 方法可以截取不超过4个进程来放入流中。最后,迭代出它们的所有信息。

以下是输出结果:

PROCESS INFORMATION =================== Process id: 8036 Command: C:\Windows\explorer.exe Arguments: Command line: Start time: 2017-03-02T16:21:14.436Z Run time duration: 299328ms Owner: jeff\jeffrey PROCESS INFORMATION =================== Process id: 10200 Command: C:\Windows\System32\dllhost.exe Arguments: Command line: Start time: 2017-03-02T16:21:16.255Z Run time duration: 2000ms Owner: jeff\jeffrey PROCESS INFORMATION =================== Process id: 1544 Command: C:\Program Files (x86)\WNSS\WNSS.exe Arguments: Command line: Start time: 2017-03-02T16:21:21.708Z Run time duration: 862375ms Owner: jeff\jeffrey PROCESS INFORMATION =================== Process id: 8156 Command: C:\Users\jeffrey\AppData\Local\SweetLabs App Platform\Engine\ServiceHostAppUpdater.exe Arguments: Command line: Start time: 2017-03-02T16:21:24.302Z Run time duration: 2468ms Owner: jeff\jeffrey

ProcessHandle的 children() 方法和 descendents() 方法运行结果很像allProcesses() f方法,除了它们是否是静态方法,以及返回值类型不一样之外,它们之间有一个集合从属关系,children() 是descendents()的子集,descendents()是allProcesses()的子集。

5、进程终止的触发机制

最后, ProcessHandle的 onExit() 方法返回java.util.concurrent.CompletableFuture让进程在终止时进行同步或异步操作成为可能。

在一个进程终止的时候打印出它的PID:

import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ProcessDemo { public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { Process p = new ProcessBuilder("notepad.exe").start(); ProcessHandle ph = p.toHandle(); CompletableFuture<ProcessHandle> onExit = ph.onExit(); onExit.get(); onExit.thenAccept(ph_ -> System.out.printf("PID %d terminated%n", ph_.getPid())); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/47d750fb3af6f60f18eb68311710a064.html