How do I get operating system process information using ProcessHandle?

Java 9 introduced the ProcessHandle API, which allows us to interact with and retrieve information about native processes. Here’s how we can use ProcessHandle to get information about operating system processes:

We can list all the processes currently running on the system and print their details:

package org.kodejava.example.lang;

import java.time.Duration;
import java.time.Instant;

public class ProcessHandleExample {
    public static void main(String[] params) {
        ProcessHandle.allProcesses()
                .forEach(process -> {
                    long pid = process.pid();
                    ProcessHandle.Info info = process.info();
                    String cmd = info.command().orElse("");
                    String[] args = info.arguments().orElse(new String[0]);
                    Instant startTime = info.startInstant().orElse(null);
                    Duration cpuUsage = info.totalCpuDuration().orElse(Duration.ZERO);

                    System.out.println("PID        = " + pid);
                    System.out.println("Command    = " + cmd);
                    System.out.println("Args       = " + String.join(" ", args));
                    System.out.println("Start Time = " + startTime);
                    System.out.println("CPU Usage  = " + cpuUsage);
                    System.out.println("------------");
                });
    }
}

If we want to get information about a specific process, we can use their process ID (PID):

package org.kodejava.example.lang;

import java.time.Duration;
import java.time.Instant;
import java.util.Optional;

public class SpecificProcessInfo {
    public static void main(String[] params) {
        // Replace with the PID of the process you want to query
        long pid = 33656;

        // Get the ProcessHandle of the specific process
        Optional<ProcessHandle> processHandle = ProcessHandle.of(pid);
        if (processHandle.isPresent()) {
            ProcessHandle process = processHandle.get();
            pid = process.pid();
            ProcessHandle.Info info = process.info();
            String cmd = info.command().orElse("");
            String[] args = info.arguments().orElse(new String[0]);
            Instant startTime = info.startInstant().orElse(null);
            Duration cpuUsage = info.totalCpuDuration().orElse(Duration.ZERO);

            System.out.println("PID        = " + pid);
            System.out.println("Command    = " + cmd);
            System.out.println("Args       = " + String.join(" ", args));
            System.out.println("Start Time = " + startTime);
            System.out.println("CPU Usage  = " + cpuUsage);
            System.out.println("------------");
        } else {
            System.out.println("No process found with PID: " + pid);
        }
    }
}

Output:

PID        = 33656
Command    = C:\Users\wayan\AppData\Local\Programs\IntelliJ IDEA Ultimate\bin\idea64.exe
Args       = 
Start Time = 2024-07-22T03:14:07.825Z
CPU Usage  = PT46M27.484375S
------------

Explanation

  • ProcessHandle.allProcesses(): returns a stream of all processes currently running on the system.
  • ProcessHandle.of(pid): returns an Optional<ProcessHandle> for the process with the given PID.
  • ProcessHandle.Info: contains information about a process, such as its command, arguments, start time, and CPU usage.
  • info.command(): returns an Optional<String> with the command used to start the process.
  • info.arguments(): returns an Optional<String[]> with the arguments passed to the process.
  • info.startInstant(): returns an Optional<Instant> with the start time of the process.
  • info.totalCpuDuration(): returns an Optional<Duration> with the total CPU time used by the process.

Using the ProcessHandle API in Java 9 and later makes it straightforward to get detailed information about operating system processes.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.