Which API does Java's jps tool use internally?
Asked Answered
M

3

5

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.

Methionine answered 10/10, 2011 at 13:4 Comment(0)
T
8

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.

Therm answered 10/10, 2011 at 13:11 Comment(1)
This is correct. I looked at the code for JPS class in sun.tools.jps.JPS and sun.tools.jstatdMethionine
B
5

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.

Biagi answered 10/10, 2011 at 13:31 Comment(0)
P
1

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

Past answered 10/10, 2011 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.