How to get the parent process of the Process API in Java 9?

JavaObject Oriented ProgrammingProgramming

ProcessHandle interface allows us to perform some actions, and check the state of a process. It provides the process’s native pid, start time, CPU time, user, parent process, and descendants. We can get access to a parent process by calling the parent() method, and the return value is Optional. It is empty if the child process doesn't have a parent or if the parent is not available.

Syntax

Optional<ProcessHandle> parent()

Example

import java.io.*;

public class ParentProcessTest {
   public static void main(String args[]) {
      try {
         Process notepadProcess = new ProcessBuilder("notepad.exe").start();
         ProcessHandle parentHandle = notepadProcess.toHandle().parent().get();
         System.out.println("Parent Process Native PID: "+ parentHandle.pid());
      } catch(IOException e) {
         e.printStackTrace();
      }
   }
}

In the above example, a "notepad" application will be launched, and also prints the parent process native PID.

Output

Parent Process Native PID : 7108
raja
Published on 16-Mar-2020 11:51:47
Advertisements