Concurrency 中级

使用 ProcessHandle 检查和管理操作系统进程。

✕ Java 8
Process p = Runtime.getRuntime()
    .exec("ls -la");
int code = p.waitFor();
// no way to get PID
// no easy process info
✓ Java 9+
ProcessHandle ph =
    ProcessHandle.current();
long pid = ph.pid();
ph.info().command()
    .ifPresent(IO::println);
ph.children().forEach(
    c -> IO.println(c.pid()));
发现此代码有问题? 告诉我们。
🔍

完整信息

访问 PID、命令、参数、启动时间、CPU 使用率。

👶

子进程管理

列出和监控子进程。

🔔

终止回调

进程终止时获得通知。

旧方式
Runtime.exec()
现代方式
ProcessHandle
自 JDK
9
难度
中级
现代 Process API
可用

自 JDK 9 起广泛可用(2017 年 9 月)

ProcessHandle 提供 PID、进程信息(命令、参数、启动时间)以及监控子进程的能力。ProcessBuilder 提供了对 stdin/stdout/stderr 的精细控制。

分享 𝕏 🦋 in