Skip to content

Instantly share code, notes, and snippets.

@ChinaXing
Last active September 13, 2017 08:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ChinaXing/6044ef2da3cb7075264c to your computer and use it in GitHub Desktop.
Save ChinaXing/6044ef2da3cb7075264c to your computer and use it in GitHub Desktop.
attach to JVM use java attach API
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.util.List;
public class ListVM{
public static void main(String[] args){
List<VirtualMachineDescriptor> vmList = VirtualMachine.list();
for(VirtualMachineDescriptor vm : vmList){
System.out.println("name: " + vm.displayName() + " id :" + vm.id());
try{
VirtualMachine vm0 = VirtualMachine.attach(vm.id());
// load agent, agnet class's agentmain will be invoked.
vm0.loadAgent("/root/tmp/ChinaAgent.jar");
System.out.println("Load agent done.");
vm0.detach();
}catch(Exception e) {
System.out.println("exception : " + e.getMessage());
}
}
}
}
@ChinaXing
Copy link
Author

compile :

javac -cp /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.51.x86_64/lib/tools.jar ListVM.java 

run :

 java -cp /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.51.x86_64/lib/tools.jar ListVM

@ChinaXing
Copy link
Author

tools.jar class path needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment