Enumerating live processes in the system
In Windows, you open the Windows Task Manager
to view the processes currently active, and in Linux you use the ps
command with its varied options to view the processes along with other details, such as user, time spent, command, and so on.
In Java 9, a new API was added, called ProcessHandle
, which deals with controlling and getting information about the processes. One of the methods of the API is allProcesses()
, which returns a snapshot of all the processes visible to the current process. In this recipe, we will look at how the method works and what information we can extract from the API.
How to do it...
Follow these steps:
- Use the
allProcesses()
method on theProcessHandle
interface to get a stream of the currently active processes:
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
- Iterate over the stream using
forEach()
, and pass a lambda expression to print the details available:
liveProcesses...