Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to traverse a process tree of Process API in Java 9?
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 {
<strong>Runtime.getRuntime().exec</strong>("<strong>cmd</strong>");
System.out.println("Showing children processes:");
<strong>ProcessHandle </strong>processHandle = <strong>ProcessHandle.current()</strong>;
processHandle.<strong>children()</strong>.forEach(childProcess ->
System.out.println("PID: " + <strong>childProcess.pid()</strong> + " Command: " + <strong>childProcess.info().command().get()</strong>));
System.out.println("Showing descendant processes:");
processHandle.<strong>descendants()</strong>.forEach(descendantProcess ->
System.out.println("PID: " + <strong>descendantProcess.pid()</strong> + " Command: " + <strong>descendantProcess.info().command().get()</strong>));
}
}
Output
<strong>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</strong>
Advertisements
