How to print pid, info, children, and destroy processes in JShell in Java 9?


JShell is a Java Shell tool used to execute simple java statements like classes, methods, interfaces, enums, and etc.. evaluates it, and prints the result in a command-line prompt.

Java has improved Process API to manage and control operating system processes. ProcessHandle interface identifies and provides control of native processes, methods to check processes liveness, and destroy the process. ProcessHandle.Info interface gives an Information snapshot of a process.

In the below code snippet, we can print pid, info, children, and destroy processes of Process API.in JShell tool.

Snippet

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[Tutorialspoint\User], cmd: C:\Program Files\Java\jdk-9.0.4\bin\java.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[Tutorialspoint\User], cmd: C:\Program Files\Java\jdk-9.0.4\bin\java.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)

Updated on: 03-May-2020

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements