ProcessHandle (Java 9) cho phép thực hiện hành động và kiểm tra trạng thái process native. Cung cấp: PID, start time, CPU time, arguments, command, user, parent process, descendants.
Các khả năng của ProcessHandle
- Trả về
ProcessHandle.Infochứa thông tin chi tiết process. - Lấy PID của process.
- Kiểm tra process còn sống (
isAlive()). - Lấy snapshot direct children (
children()). - Lấy snapshot all descendants (
descendants()). - Lấy snapshot tất cả process đang chạy (
allProcesses()). - Cho phép destroy process (
destroy(),destroyForcibly()). - Trả về
CompletableFuture<ProcessHandle>khi process terminated (onExit()).
ProcessHandle.Info
Snapshot thông tin process:
- Command
- Arguments
- Command line
- Start time
- CPU time
- User
Ví dụ: PID và isAlive của process hiện tại
import java.util.Optional;
public class ProcessHandleTest {
public static void main(String args[]) {
long pid = ProcessHandle.current().pid();
ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("PID: " + currentProcess.pid());
Optional<ProcessHandle> processHandle = ProcessHandle.of(pid);
boolean isAlive = processHandle.isPresent() && processHandle.get().isAlive();
System.out.println(isAlive);
}
}
Kết quả
PID: 6484 true
Ví dụ nâng cao: Theo dõi process con
ProcessHandle current = ProcessHandle.current();
current.children().forEach(child ->
System.out.println("Child PID: " + child.pid() + ", CMD: " + child.info().command().orElse("N/A")));
// Đợi process con kết thúc
current.onExit().thenAccept(ph ->
System.out.println("Process " + ph.pid() + " exited"));
ProcessHandle API thay thế JNI, JNA, Runtime.exec() parsing – cung cấp cách chuẩn, type-safe, cross-platform quản lý process.