How to get OS process details of specific application using SIGAR or OSHI APIs in Java?

851 Views Asked by At

Does SIGAR or OSHI or any other similar APIs provide out of the box and most importantly, generic capabilities to pull out the OS process information?

My requirement is to get the PIDs and some other details of all OS processes of a specific program, e.g. Chrome.

As below, I wrote my own implementation but I'll have to come up with a little different method for Unix, Mac, Solaris etc. as below is specific to Windows. Just to keep things generic, I am wondering if there is any OOTB method in SGIAR / OSHI.

public static List<String> getNodeDetailsFromWinOs(){
        List<String> nodeList = new ArrayList<String>();
        String process;
        Process p = Runtime.getRuntime().exec("tasklist.exe /nh");
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((process = input.readLine()) != null) 
                        {
                          nodeList.add(process.substring(10, process.indexOf(".")));
                        }
        input.close();
        return nodeList;    
    }
2

There are 2 best solutions below

0
Daniel Widdis On BEST ANSWER

OSHI's OSProcess class provides this capability out of the box, for Windows, macOS, Linux, AIX, Solaris, and FreeBSD.

SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
OSProcess[] procs = os.getProcesses(0, null);

for (OSProcess p : procs) {
    if (p.getName().contains("Chrome")) {
        // do stuff with p
    }
}

You may also find the p.getParentProcessPid() and os.getChildProcesses(pid) methods useful to identify other processes (not including the name "Chrome") associated with the parent Chrome process.

In addition, as of Java 9, the core JDK includes a ProcessHandle class with some basic information including the PID.

0
Stack2Heap On

I could not find it earlier because SIGAR docs were not available publically. I found them here on this link. This contains doc and API Ref.

By the way, method public long[] find(java.lang.String query) throws SigarException in class ProcessFinder can be used to get the OS details.

SIGAR API ref can be downloaded from https://sourceforge.net/projects/sigar/