Java 9 đã cải tiến Process API, giúp quản lý và điều khiển tiến trình hệ điều hành. Trước Java 9, việc quản lý tiến trình OS bằng chương trình Java rất khó khăn. Kể từ Java 9, các lớp và interface mới được thêm để điều khiển tiến trình OS qua Java. Các interface mới như ProcessHandle và ProcessHandle.Info được thêm, cũng như các phương thức mới cho lớp Process.
Trong ví dụ dưới đây, chúng ta có thể duyệt cây tiến trình (children và descendant processes) của Process API.
Ví dụ
import java.io.IOException;
public class ProcessTreeTest {
public static void main(String args[]) throws IOException {
Runtime.getRuntime().exec("cmd");
System.out.println("Hiển thị tiến trình con:");
ProcessHandle processHandle = ProcessHandle.current();
processHandle.children().forEach(childProcess ->
System.out.println("PID: " + childProcess.pid() + " Command: " + childProcess.info().command().get()));
System.out.println("Hiển thị tiến trình cháu:");
processHandle.descendants().forEach(descendantProcess ->
System.out.println("PID: " + descendantProcess.pid() + " Command: " +
descendantProcess.info().command().get()));
}
}
Kết quả
Hiển thị tiến trình con:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
Hiển thị tiến trình cháu:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
PID: 2256 Command: C:\WINDOWS\System32\conhost.exe