O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Use the allProcesses() method on the ProcessHandle interface to get a stream of the currently active processes:
         Stream<ProcessHandle> liveProcesses =                        ProcessHandle.allProcesses();
  1. Iterate over the stream using forEach() and pass a lambda expression to print the details available:
         liveProcesses.forEach(ph -> {
           ProcessHandle.Info phInfo = ph.info();
           System.out.println(phInfo.command().orElse("") +" " + 
                              phInfo.user().orElse(""));
         });

You can get the complete code from chp8/9_enumerate_all_processes.

We have provided a utility script called run.sh, which you can use to compile and run the code: sh run.sh.

The output we get is as follows:

 

In the preceding output, we are printing the command name as well as the user of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required