Listing children

To get Stream of process handles for controlling children, the static method processHandle.children() should be used. This will create a snapshot of the children processes of the process represented by processHandle and create Stream. Since processes are dynamic, there is no guarantee that during the code execution, while our program attends to the handles, all children processes are still active. Some of them may terminate and our process may spawn new children, perhaps from a different thread. Thus, the code should not assume that each of the ProcessHandle elements of Stream represents an active and running process. 

The following program starts 10 Command Prompts in Windows and then counts the number of children processes and prints them to a standard output:

import java.io.IOException;

public class ChildLister {
public static void main(String[] args) throws IOException {
for (int i = 0; i < 10; i++) {
new ProcessBuilder().command("cmd.exe").start();
}
System.out.println("Number of children :" +
ProcessHandle.current().children().count());
}
}

Executing the program will result in the following:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset