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.
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
jps
uses an internal class -MonitoredHost
of the Oracle/Sun JRE. TheactiveVMs()
method is used to obtain the list of all active VMs on a host. You can refer to the source of thesun.tools.jps.Jps
class of OpenJDK, to find out how thejps
tool works under the hood.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.