Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีดึง Process ID (PID) ของกระบวนการที่ทำงานอยู่ใน Java 9

Java 9 ปรับปรุง Process API สำหรับดึง PID, children, descendants, รายการ process ทั้งหมด ข้อมูลเป็น snapshot ของ process ที่ทำงานอยู่

ใช้เมธอด pid() ของ ProcessHandle เพื่อดึง PID

ตัวอย่างโค้ด

public class GetPID {
    public static void main(String args[]) {
        ProcessHandle ph = ProcessHandle.current();
        
        System.out.println("PID: " + ph.pid());
        System.out.println("Command: " + ph.info().command().orElse("N/A"));
        System.out.println("CPU Duration: " + ph.info().totalCpuDuration().get().getSeconds() + " seconds");
    }
}

ผลลัพธ์ตัวอย่าง

PID of the running Process: 4248
Command: C:\Program Files\Java\jdk-9.0.4\bin\java.exe
CPU Duration: 0 seconds