通过线程监控Java进程,完成attach agent


import java.io.IOException;
import java.util.List;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

public class AttachAgent {
  // 一个运行 Attach API 的线程子类
  static class AttachThread extends Thread {

    private final List listBefore;

    private final String jar;

    AttachThread(String attachJar, List vms) {
      listBefore = vms; // 记录程序启动时的 VM 集合
      jar = attachJar;
    }

    public void run() {
      VirtualMachine vm = null;
      List listAfter = null;
      try {
        int count = 0;
        while (true) {
          listAfter = VirtualMachine.list();
          for (VirtualMachineDescriptor vmd : listAfter) {
            
            System.out.println("displayName:" + vmd.displayName());
            System.out.println("toString:" + vmd.toString());
            
            
            
            if (!listBefore.contains(vmd)) {
              // 如果 VM 有增加,我们就认为是被监控的 VM 启动了
              // 这时,我们开始监控这个 VM
              vm = VirtualMachine.attach(vmd);
              break;
            }
          }
          Thread.sleep(500);
          count++;
          if (null != vm || count >= 100) {
            break;
          }
        }
        vm.loadAgent(jar);
        vm.detach();
      } catch (Exception e) {

      }
    }
  }

  public static void main(String[] args) throws InterruptedException {
    new AttachThread("D:\\indigo\\eclipse\\workspace\\AttachAgent\\agent.jar", VirtualMachine.list()).start();
    
    //new AttachThread("/home/admin/attach/agent.jar", VirtualMachine.list()).start();
  }
}


转载地址:http://memory.blog.51cto.com/6054201/1174700

你可能感兴趣的:(Java)