Java 9 ปรับปรุง Process API จัดการ process ของ OS ได้ดีขึ้น มี interface ใหม่: ProcessHandle และ ProcessHandle.Info
สามารถ traverse process tree (children และ descendants) ได้
ตัวอย่างโค้ด
import java.io.IOException;
public class ProcessTreeExample {
public static void main(String args[]) throws IOException {
// เริ่ม child process (cmd.exe)
Runtime.getRuntime().exec("cmd");
System.out.println("Child processes:");
ProcessHandle current = ProcessHandle.current();
current.children().forEach(child ->
System.out.println("PID: " + child.pid() + " Command: " + child.info().command().orElse("N/A")));
System.out.println("\nDescendant processes:");
current.descendants().forEach(desc ->
System.out.println("PID: " + desc.pid() + " Command: " + desc.info().command().orElse("N/A")));
}
}
ผลลัพธ์ตัวอย่าง
Child processes: PID: 5092 Command: C:\WINDOWS\System32\cmd.exe Descendant processes: PID: 5092 Command: C:\WINDOWS\System32\cmd.exe PID: 2256 Command: C:\WINDOWS\System32\conhost.exe