在ProcessHandle简单的"Dockerized"Java程序中尝试使用Java 9中的新API时,我发现在检索正在运行的进程的进程ID时,行为方面存在差异.特别是在调用方法时ProcessHandle.pid(),Docker上生成的PID与主机上显示的本机ID不同,尽管文档说该方法"返回进程的本机进程ID".另外,结果之间存在差异ProcessHandle.allProcesses().
为了演示,以下程序执行以下操作:
public static void main(String[] args) {
System.out.println("### Current process info ###");
ProcessHandle currentProcess = ProcessHandle.current();
printInfo(currentProcess);
System.out.println();
// Fork a child process that lasts for a few seconds
spawnProcess("jshell --startup ./sleep.txt");
printAllVisibleProcesses();
}
private static void printAllVisibleProcesses() {
System.out.println("### Visible processes info ###");
ProcessHandle.allProcesses().forEach(ProcessHandleExamples::printInfo);
System.out.println();
}
private static void spawnProcess(String command) {
System.out.println("Spawning: " + command);
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
} …Run Code Online (Sandbox Code Playgroud)