Java Attach机制,初次接触是长成以下这样的:
VirtualMachine.attach(pid);
当时只是惊叹于java提供了这样强大的Api,但是不知道背后究竟发生了什么;带着一种程序员天生具备的使命感开始进行了探索之旅,最终跟进去后其实是下面一段Java代码:
BsdVirtualMachine(AttachProvider var1, String var2) throws AttachNotSupportedException, IOException {
super(var1, var2);
int var3;
try {
var3 = Integer.parseInt(var2);
} catch (NumberFormatException var22) {
throw new AttachNotSupportedException("Invalid process identifier");
}
this.path = this.findSocketFile(var3);
if(this.path == null) {
File var4 = new File(tmpdir, ".attach_pid" + var3);
createAttachFile(var4.getPath());
try {
sendQuitTo(var3);
int var5 = 0;
long var6 = 200L;
int var8 = (int)(this.attachTimeout() / var6);
do {
try {
Thread.sleep(var6);
} catch (InterruptedException var21) {
;
}
this.path = this.findSocketFile(var3);
++var5;
} while(var5 <= var8 && this.path == null);
if(this.path == null) {
throw new AttachNotSupportedException("Unable to open socket file: target process not responding or HotSpot VM not loaded");
}
} finally {
var4.delete();
}
}
checkPermissions(this.path);
int var24 = socket();
try {
connect(var24, this.path);
} finally {
close(var24);
}
}
然后解析下上面这段代码:
首先去查询socket文件,如果文件不存在,就会再去创建一个.attach_pid<pid>相关的文件,然后向这个<pid>的进程发送了SIGQUIT命令,接着进了一个循环中,不断等待一段时间,并且去检查socket文件的存在性,一旦超时后再没有等到socket文件的出现,则会抛出“Unable to open socket file: target process not responding or HotSpot VM not loaded”的异常了;但是如果socket文件此时存在了或者说从刚开始的时候socket文件就一直存在了,那么就会去直接检查socket文件的权限,然后进行socket连接,最后关闭socket连接;其实到这里,也只是稍微描述了这个attach的过程,但是其实过程中还是有很多疑问点没有去跟踪到的:
1.这个.attach_pid<pid>文件是干嘛的?
2.为什么要去等待这个socket文件的生成,这个文件生成了会怎么样?
3.为什么还会向<pid>这个进程发送SIGQUIT命令呢,怎么看出来是发送SIGQUIT命令的呢?
要解决以上的问题,就要再次深入Native的代码去看底层实现的细节,会在下一篇《Java Attach机制之Native篇》中跟踪到










网友评论