How to traverse a process tree of Process API in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 has improved Process API, and it helps to manage and control operating system processes. Before Java 9, it has been difficult to manage and control operating system processes using Java programs. Since Java 9, new classes and interfaces have added to control the operating system process through Java programs. New interfaces like ProcessHandle and ProcessHandle.Info have added, and also new methods have added to Process class.

In the below example, we can traverse a process tree (children and descendant processes) of Process API.

Example

import java.io.IOException;

public class ProcessTreeTest {
   public static void main(String args[]) throws IOException {
      Runtime.getRuntime().exec("cmd");
     
      System.out.println("Showing children processes:");
      ProcessHandle processHandle = ProcessHandle.current();
      processHandle.children().forEach(childProcess ->
              System.out.println("PID: " + childProcess.pid() + " Command: " + childProcess.info().command().get()));
     
      System.out.println("Showing descendant processes:");
      processHandle.descendants().forEach(descendantProcess ->
              System.out.println("PID: " + descendantProcess.pid() + " Command: " +   descendantProcess.info().command().get()));
   }
}

Output

Showing children processes:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
Showing descendant processes:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
PID: 2256 Command: C:\WINDOWS\System32\conhost.exe
raja
Published on 08-Apr-2020 09:04:08
Advertisements