How can we get an ID of the running process in Java 9?


Java 9 has added improvements to Process API for getting PID of running process, getting children and/or descendants of a process, and also added a new class that helps to list out all running processes, getting information about an arbitrary process, and traversing process tree. The information returned by these methods can be a snapshot of processes running on the OS.

In the below example, we can get an ID of the running process by using the pid() method of ProcessHandle.

Example

public class ProcessHandleTest {
   public static void main(String args[]) {
      ProcessHandle processHandle = ProcessHandle.current();
      System.out.println("PID of running Process: " + processHandle.pid());
      System.out.println("Command: " + processHandle.info().command().orElse("N/A"));
      System.out.println("CPU Duration: " + processHandle.info().totalCpuDuration().get().getSeconds() + " seconds");
   }
}

Output

PID of the running Process: 4248
Command: C:\Program Files\Java\jdk-9.0.4\bin\java.exe
CPU Duration: 0 seconds

Updated on: 07-Apr-2020

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements