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

วิธีแสดง PID, ข้อมูลโปรเซส, โปรเซสลูก และทำลายโปรเซสใน JShell Java 9

JShell เป็นเครื่องมือ Java Shell ที่ใช้รันคำสั่ง Java แบบง่ายๆ เช่น คลาส เมธอด อินเทอร์เฟซ และ enum แล้วประเมินผลและแสดงผลใน command-line prompt

Java 9 ปรับปรุง Process API เพื่อจัดการและควบคุมโปรเซสของระบบปฏิบัติการ ProcessHandle interface ใช้ระบุและควบคุม native processes มีเมธอดตรวจสอบ liveness และ ทำลายโปรเซส ส่วน ProcessHandle.Info interface ให้ข้อมูล snapshot ของโปรเซส

ตัวอย่างคำสั่งใน JShell

jshell> ProcessHandle currentProcess = ProcessHandle.current();
currentProcess ==> 3960

jshell> System.out.println("Current Process Id: = " + currentProcess.pid());
Current Process Id: = 3960

jshell> currentProcess.info();
$3 ==> [user: Optional[Tutorialspoint\User], cmd: C:\Program Files\Java\jdk-9.0.4\bin\java.exe, startTime: Optional[2020-05-03T06:43:37.510Z], totalTime: Optional[PT1.265625S]]

jshell> currentProcess.pid();
$4 ==> 3960

jshell> ProcessHandle.of(3960)
$5 ==> Optional[3960]

jshell> $5.get()
$6 ==> 3960

jshell> $6.info()
$7 ==> [user: Optional[Tutorialspoint\User], cmd: C:\Program Files\Java\jdk-9.0.4\bin\java.exe, startTime: Optional[2020-05-03T06:43:37.510Z], totalTime: Optional[PT1.390625S]]

jshell> Stream<ProcessHandle> childProc = ProcessHandle.current().children();
childProc ==> java.util.stream.ReferencePipeline$2@6895a785

jshell> childProc.count()
$10 ==> 1

jshell> childProc.forEach(procHandle -> { 
    System.out.println(procHandle.destroy() ? "Could not kill process " + procHandle.pid() : "Terminated " + procHandle.pid()); 
});
| java.lang.IllegalStateException thrown: stream has already been operated upon or closed
|     at AbstractPipeline.evaluate (AbstractPipeline.java:229)
|     at ReferencePipeline.forEach (ReferencePipeline.java:430)
|     at (#11:1)

คำอธิบายสำคัญ

  • ProcessHandle.current() - ได้ ProcessHandle ของโปรเซสปัจจุบัน
  • pid() - ได้ Process ID
  • info() - ได้ข้อมูล snapshot ของโปรเซส (user, command, start time, CPU time)
  • ProcessHandle.of(pid) - หา ProcessHandle จาก PID
  • children() - ได้ Stream ของโปรเซสลูก (child processes)
  • destroy() - พยายามทำลายโปรเซสแบบ graceful
  • destroyForcibly() - บังคับทำลายโปรเซสทันที

ข้อสังเกตจากตัวอย่าง

ในคำสั่งสุดท้ายเกิด IllegalStateException เพราะ Stream ถูกใช้งานไปแล้ว (จาก childProc.count()) ไม่สามารถใช้ forEach ซ้ำได้ ควรสร้าง Stream ใหม่หรือเก็บผลลัพธ์ไว้ก่อน