Which API does Java's jps tool use internally?

2020-07-13 10:26发布

问题:

I need to recreate the functionalities of the jps tool programmatically. I need to find out all Java running processes along with their id so I can attach to that process (similar to what JConsole does).

I thought the VirtualMachine API would help, but did not get expected result when I run the following

public class ProcessList {
    public static void main(String[] args){
        List<VirtualMachineDescriptor> vms = VirtualMachine.list();
        for(VirtualMachineDescriptor vm : vms){
            System.out.println (vm.id());
        }
    }
}

When I run the code above, it returns just one ID, but when I run jps on the same machine I see several other processes.

回答1:

jps uses an internal class - MonitoredHost of the Oracle/Sun JRE. The activeVMs() method is used to obtain the list of all active VMs on a host. You can refer to the source of the sun.tools.jps.Jps class of OpenJDK, to find out how the jps tool works under the hood.



回答2:

This is the correct API, ultimately 'MonitoredHost#activeVMs()' and 'VirtualMachine.list()' use the same discovery code via jstat technology. Do you run jps on the command line as a different user? In that case, you would see different JVMs.

See here how JPS is implemented.



回答3:

you can do following : 1) Create platform specific script files (.bat for windows, .sh for linux etc) 2)Use "wmic process"(Windows), "ps -ef"(linux) etc commands in those scripts to list the processes (pipe on the result to get the java processes). 3)Launch the above scripts using Runtime's API and get the output result