Listing descendants

Listing the descendants is very similar to listing children, but if we call the processHandle.descendants() method then Stream will contain all the children processes and the children processes of those processes, and so on.

The following program starts Command Prompts with command-line arguments so that they also spawn another cmd.exe that terminates:

import java.io.IOException;
import java.util.stream.Collectors;

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

Running the command a few times will result in the following, nondeterministic output:

The output clearly demonstrates that when Stream of the descendants is created not all processes are alive. The sample code starts 10 processes and each of them starts another. Stream does not have 20 elements because some of these subprocesses were terminated during processing.

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

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