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

วิธีดู Snapshot ข้อมูลโปรเซสด้วย Process API ใน Java 9

Java 9 ปรับปรุง Process API โดยเพิ่มเมธอดใหม่และ interface ใหม่ 2 ตัวคือ ProcessHandle และ ProcessHandle.Info เพื่อดูรายละเอียดของโปรเซสและข้อมูลต่างๆ

ProcessHandle interface ใช้ระบุและควบคุม native processes แต่ละโปรเซสสามารถตรวจสอบ liveness, แสดง children, ดูข้อมูลโปรเซส หรือ destroy ได้ ส่วน ProcessHandle.Info interface ให้ข้อมูล snapshot เกี่ยวกับโปรเซส

Syntax

ProcessHandle.Info info()

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

public class ProcessSnapShotTest {
    public static void main(String[] args) {
        // ได้ ProcessHandle ของโปรเซสปัจจุบัน
        ProcessHandle currentProcessHandleImpl = ProcessHandle.current();
        
        // Process snapshot ของโปรเซสปัจจุบันด้วย ProcessHandle.Info
        ProcessHandle.Info processInfo = currentProcessHandleImpl.info();
        
        System.out.println("Process snapshot of the current running process:");
        System.out.println("User: " + processInfo.user().get());
        System.out.println("Start Time: " + processInfo.startInstant().get());
    }
}

ผลลัพธ์

Process snapshot of the current running process:
User: Tutorialspoint\User
Start Time: 2020-05-01T05:44:41.458Z

เมธอดสำคัญของ ProcessHandle.Info

เมธอด คืนค่า คำอธิบาย
user() Optional<String> ผู้ใช้ที่รันโปรเซส
command() Optional<String> คำสั่งที่ใช้เริ่มโปรเซส
commandLine() Optional<String> คำสั่งเต็มรวม arguments
startInstant() Optional<Instant> เวลาเริ่มต้นโปรเซส
totalCpuDuration() Optional<Duration> CPU time ทั้งหมดที่ใช้
arguments() Optional<String[]> Arguments array

ข้อดีของ Process API ใหม่

  • ไม่ต้องใช้ native code หรือ JNI
  • Cross-platform support
  • เข้าถึงข้อมูลโปรเซสได้ง่ายและปลอดภัย
  • รองรับการจัดการโปรเซสลูก (children processes)