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

Stack2Heap :

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;    
    }
Daniel Widdis :

OSHI's OSProcess class provides this capability out of the box, for Windows, macOS, Linux, 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310354&siteId=1