Java 9 : How to list all processes running on the OS

Points to Remember

  1. Java 9 introduced the new Process Api in java.lang package.
  2. ProcessHandle interface can be used to perform operations with processes like start, destroy, list processes.

Read More

List all Processes running on the OS.

To get all the processes running on the OS you can use the static method allProcesses() of the ProcessHandle, this will return a Stream<ProcessHandle> stream of process handles which can be used to get information about each process. The below example shows how we can list all the running processes.

import java.lang.ProcessHandle;
import java.util.stream.Stream;

/**
 * @author ekiras
 */
public class ListAllProcesses {

    public static void main(String[] args){
        allProcesses();
    }

    public static void allProcesses() {
        System.out.println("Process list:");
        Stream<ProcessHandle> processStream = ProcessHandle.allProcesses();
        processStream.forEach(e -> printProcessInfo(e));
    }

    public static void printProcessInfo(ProcessHandle processHandle){
        System.out.println("---------------------------------------------------------");
        System.out.println(" Process Id :: " + processHandle.getPid());
        System.out.println(" Process isAlive() :: " + processHandle.isAlive());
        System.out.println(" Process children :: " + processHandle.children().count());
        System.out.println(" Process supportsNormalTermination() :: " + processHandle.supportsNormalTermination());
        System.out.println(" Process Info :: " + processHandle.info().toString());

    }

}

The above code will produce the following output on console.

Process list:
---------------------------------------------------------
 Process Id :: 1
 Process isAlive() :: true
 Process children :: 0
 Process supportsNormalTermination() :: true
 Process Info :: [user: Optional[root], cmd: /bin/bash, startTime: Optional[2016-11-14T05:24:57.150Z], totalTime: Optional[PT0.02S]]
---------------------------------------------------------
 Process Id :: 15
 Process isAlive() :: true
 Process children :: 1
 Process supportsNormalTermination() :: true
 Process Info :: [user: Optional[root], cmd: /bin/bash, startTime: Optional[2016-11-14T05:25:06.670Z], totalTime: Optional[PT0.08S]]
---------------------------------------------------------
 Process Id :: 449
 Process isAlive() :: true
 Process children :: 0
 Process supportsNormalTermination() :: true
 Process Info :: [user: Optional[root], cmd: /opt/jdk-9/bin/java, args: [ListAllProcesses], startTime: Optional[2016-11-14T07:38:41.240Z], totalTime: Optional[PT0.35S]]

No comments:

Powered by Blogger.