如何在 Java 9 中獲取 Process API 的父程序?


ProcessHandle 介面允許我們執行某些操作,並檢查程序的狀態。它提供程序的本地pid開始時間CPU 時間使用者父程序子程序。我們可以透過呼叫 parent() 方法來訪問父程序,返回值為Optional。如果子程序沒有父程序或父程序不可用,則它為空。

語法

Optional<ProcessHandle> parent()

示例

import java.io.*;

public class ParentProcessTest {
   public static void main(String args[]) {
      try {
         Process notepadProcess = new ProcessBuilder("notepad.exe").start();
         ProcessHandle parentHandle = notepadProcess.toHandle().parent().get();
         System.out.println("Parent Process Native PID: "+ parentHandle.pid());
      } catch(IOException e) {
         e.printStackTrace();
      }
   }
}

在上面的示例中,將啟動“記事本”應用程式,並列印父程序的本地 PID。

輸出

Parent Process Native PID : 7108

更新於: 16-3-2020

648 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.