首页 > 文章列表 > 在Java 9的JShell中如何打印pid、info、children和销毁进程?

在Java 9的JShell中如何打印pid、info、children和销毁进程?

192 2023-09-06

JShell是一个 Java Shell 工具,用于执行简单的 java 语句,例如类、方法、接口、枚举等。对其进行评估,并将结果打印在命令行提示符。

Java 改进了Process API来管理和控制操作系统进程。 ProcessHandle接口识别并提供对本机进程的控制、检查进程活动性销毁进程的方法过程。 ProcessHandle.Info 接口提供进程的信息快照

在下面的代码片段中,我们可以打印pid 进程API<的信息子进程销毁进程/strong>.in JShell 工具。

代码片段

jshell> ProcessHandle currentProcess = ProcessHandle.current();
currentProcess ==> 3960

jshell> System.out.println("Current Process Id: = " + currentProcess.pid());
Current Process Id: = 3960

jshell> currentProcess.info();
$3 ==> [user: Optional[TutorialspointUser], cmd: C:Program FilesJavajdk-9.0.4binjava.exe, startTime: Optional[2020-05-03T06:43:37.510Z], totalTime: Optional[PT1.265625S]]

jshell> currentProcess.pid();
$4 ==> 3960

jshell> ProcessHandle.of(3960)
$5 ==> Optional[3960]

jshell> $5.get()
$6 ==> 3960

jshell> $6.info()
$7 ==> [user: Optional[TutorialspointUser], cmd: C:Program FilesJavajdk-9.0.4binjava.exe, startTime: Optional[2020-05-03T06:43:37.510Z], totalTime: Optional[PT1.390625S]]

jshell> Stream<ProcessHandle> childProc = ProcessHandle.current().children();
childProc ==> java.util.stream.ReferencePipeline$2@6895a785

jshell> childProc.count()
$10 ==> 1

jshell> childProc.forEach(procHandle -> { System.out.println(procHandle.destroy() ? "Could not kill process " + procHandle.pid() : "Terminated " + procHandle.pid()); });

|   java.lang.IllegalStateException thrown: stream has already been operated upon or closed
|      at AbstractPipeline.evaluate (AbstractPipeline.java:229)
|      at ReferencePipeline.forEach (ReferencePipeline.java:430)
|      at (#11:1)