← 中文资源

简体中文版本

ProcessHandle 自检当前进程

ProcessHandle.current() 拿到本进程:pid 直接可读,命令行、启动时刻等细节包在 Optional 里按可用性取用;children() 枚举子进程,可做守护与巡检判断。

阅读英文原文

实现说明

逻辑集中在类 SelfCheck和函数 main里。

使用要点

  • 演示输出是带标签的(pid =、command =、start =),每个操作都会留下自己的一行标注。

常见问题

运行「ProcessHandle 自检当前进程」会打印什么?

整个文件跑完,输出行以 pid =、command =、start = 这类前缀开头。

核心语句

.map(instant -> instant.atZone(ZoneId.systemDefault())
        .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))

代码示例

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class SelfCheck {

    public static void main(String[] args) {
        ProcessHandle self = ProcessHandle.current();
        System.out.println("pid = " + self.pid());

        ProcessHandle.Info info = self.info();
        // details like the command line and start time come from the runtime, always wrapped in Optional
        System.out.println("command = " + info.command().orElse("(unavailable)"));
        System.out.println("start   = " + info.startInstant()
                .map(instant -> instant.atZone(ZoneId.systemDefault())
                        .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
                .orElse("(unavailable)"));

        // descendant enumeration: the entry point for liveness checks or process-tree walks
        System.out.println("children = " + self.children().count());
    }
}