Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để duyệt qua cây quy trình của API quy trình trong Java 9?


Java 9 đã cải thiện API quy trình , và nó giúp quản lý và kiểm soát các quy trình của hệ điều hành. Trước Java 9, rất khó để quản lý và kiểm soát các tiến trình của hệ điều hành bằng cách sử dụng các chương trình Java. Kể từ J ava 9 , các lớp và giao diện mới đã được thêm vào để kiểm soát quá trình hệ điều hành thông qua các chương trình Java. Các giao diện mới như ProcessHandle ProcessHandle.Info đã được thêm và các phương pháp mới cũng được thêm vào Quy trình lớp học.

Trong ví dụ dưới đây, chúng ta có thể xem qua cây quy trình ( trẻ em hậu duệ quy trình) của Quy trình API.

Ví dụ

import java.io.IOException;

public class ProcessTreeTest {
   public static void main(String args[]) throws IOException {
      Runtime.getRuntime().exec("cmd");
     
      System.out.println("Showing children processes:");
      ProcessHandle processHandle = ProcessHandle.current();
      processHandle.children().forEach(childProcess ->
              System.out.println("PID: " + childProcess.pid() + " Command: " + childProcess.info().command().get()));
     
      System.out.println("Showing descendant processes:");
      processHandle.descendants().forEach(descendantProcess ->
              System.out.println("PID: " + descendantProcess.pid() + " Command: " +   descendantProcess.info().command().get()));
   }
}

Đầu ra

Showing children processes:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
Showing descendant processes:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
PID: 2256 Command: C:\WINDOWS\System32\conhost.exe