在Java 9中,负责控制和管理操作系统进程的Process API得到了显着改进. ProcessHandle类现在提供进程的本机进程ID,开始时间,累计CPU时间,参数,命令,用户,父进程和后代. ProcessHandle类还提供了检查进程活跃性和破坏进程的方法.它有onExit方法,当进程退出时,CompletableFuture类可以异步执行操作.
Tester.java
import java.time.ZoneId;import java.util.stream.Stream;import java.util.stream.Collectors;import java.io.IOException;public class Tester { public static void main(String[] args) throws IOException { ProcessBuilder pb = new ProcessBuilder("notepad.exe"); String np = "Not Present"; Process p = pb.start(); ProcessHandle.Info info = p.info(); System.out.printf("Process ID : %s%n", p.pid()); System.out.printf("Command name : %s%n", info.command().orElse(np)); System.out.printf("Command line : %s%n", info.commandLine().orElse(np)); System.out.printf("Start time: %s%n", info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()) .toLocalDateTime().toString()).orElse(np)); System.out.printf("Arguments : %s%n", info.arguments().map(a -> Stream.of(a).collect( Collectors.joining(" "))).orElse(np)); System.out.printf("User : %s%n", info.user().orElse(np)); } }
输出
您将看到以下输出.
Process ID : 5800Command name : C:\Windows\System32\notepad.exeCommand line : Not PresentStart time: 2017-11-04T21:35:03.626Arguments : Not PresentUser: administrator