Which API does Java's jps tool use internally?

2020-07-13 10:18发布

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.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-13 10:48

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

查看更多
姐就是有狂的资本
3楼-- · 2020-07-13 10:59

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.

查看更多
再贱就再见
4楼-- · 2020-07-13 11:00

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.

查看更多
登录 后发表回答