如何使用Java 9中的Process API获取进程的所有子进程?
进程处理类和相关API已在Java 9中引入。我们可以使用ProcessHandle接口和相关方法来获取pid以及其他相关进程的信息。我们需要获取进程的所有子进程,然后使用 java.lang.ProcessHandle.children() 方法。此方法返回一个流,通常是没有子进程的进程。
在下面的示例中,我们可以获取第一个进程并检索其子进程信息。
示例
import java.util.stream.Stream; import java.util.Optional; public class ChilderenProcessTest { public static void main(String args[]) throws InterruptedException { System.out.println("---------------------------"); System.out.println("Children Processes:"); <strong>Optional<ProcessHandle></strong> processHandle = <strong>ProcessHandle.allProcesses().findFirst()</strong>; processHandle.<strong>ifPresent</strong>(proc -> proc.<strong>children()</strong>.forEach(child -> System.out.println("PID: [ " + <strong>child.pid()</strong> + " ], Cmd: [ " + <strong>child.info().command()</strong> + " ]"))); } }
输出
<strong>--------------------------- Children Processes: PID: [ 0 ], Cmd: [ Optional.empty ] PID: [ 4 ], Cmd: [ Optional.empty ] PID: [ 424 ], Cmd: [ Optional.empty ] PID: [ 504 ], Cmd: [ Optional.empty ] PID: [ 560 ], Cmd: [ Optional.empty ] PID: [ 444 ], Cmd: [ Optional.empty ] PID: [ 1236 ], Cmd: [ Optional.empty ] PID: [ 1288 ], Cmd: [ Optional.empty ] PID: [ 1408 ], Cmd: [ Optional.empty ] PID: [ 1424 ], Cmd: [ Optional.empty ] PID: [ 1452 ], Cmd: [ Optional.empty ] PID: [ 1468 ], Cmd: [ Optional.empty ] PID: [ 5412 ], Cmd: [ Optional[C:\WINDOWS\System32\taskhostex.exe] ] PID: [ 3760 ], Cmd: [ Optional[C:\Program Files\Synaptics\SynTP\SynTPEnh.exe] ] PID: [ 5216 ], Cmd: [ Optional[C:\WINDOWS\explorer.exe] ] PID: [ 2460 ], Cmd: [ Optional[C:\Program Files (x86)\Dell Wireless\Bluetooth Suite\BtvStack.exe] ] PID: [ 6064 ], Cmd: [ Optional[C:\Program Files\Realtek\Audio\HDA\RtkNGUI64.exe] ] PID: [ 7172 ], Cmd: [ Optional[C:\Program Files (x86)\Google\Chrome\Application\chrome.exe] ] PID: [ 860 ], Cmd: [ Optional[C:\Program Files (x86)\Google\Chrome\Application\chrome.exe] ] PID: [ 9000 ], Cmd: [ Optional.empty ] PID: [ 4180 ], Cmd: [ Optional[C:\WINDOWS\System32\cmd.exe] ] PID: [ 3748 ], Cmd: [ Optional[C:\WINDOWS\System32\conhost.exe] ] PID: [ 3376 ], Cmd: [ Optional.empty ] PID: [ 2548 ], Cmd: [ Optional.empty ] PID: [ 1820 ], Cmd: [ Optional[C:\Program Files\Java\jdk-9.0.4\bin\java.exe] ]</strong>
以上就是如何使用Java 9中的Process API获取进程的所有子进程?的详细内容,更多请关注其它相关文章!