@boothsun
2022-01-26T05:28:40.000000Z
字数 2327
阅读 1611
JVM
jps命令用于查看当前Java进程及其pid等相关信息,同ps -ef | grep java这种命令不同的是,jps并不使用应用程序名来查找JVM实例。因此,它查找所有的java应用程序,包括即使没有使用Java执行体的那种(例如定制的启动器)。另外,jps仅查找当前用户的Java进程,而不是当前系统中的所有进程。
jps命令格式
jps [options] [hostid]
jps工具主要选项
| 选项 | 作用 |
|---|---|
| -q | 只输入LVMID,省略主类的名称 |
| -m | 输出虚拟机进程启动时传递给主类main()函数的参数。 |
| -l | 输出主类的全名,如果进程执行的是jar包,输出jar包路径。 |
| -v | 输出虚拟机进程启动时JVM参数 |
Java程序在启动以后,会在java.io.tmpdir指定的目录下,就是临时文件夹里,生成一个类似于hsperfdata_User的文件夹;在这个文件夹里(在linux中为/tmp/hsperfdata_{username}),有几个文件,名字就是java进程的pid,因此列出当前运行的java进程,只是把这个目录里的文件名列一下而已。至于系统的参数什么,就可以解析这几个文件获得。

1.每启动一个Java应用,其会在当前用户的临时目录下创建一个临时文件夹,以该应用的pid命名。
public static final String dirNamePrefix = "hsperfdata_";public static String getTempDirectory(String user) {return tmpDirName + dirNamePrefix + user + File.separator;}
2.jps则会根据这些文件,获取本地的java进程,及具体的Main CLass 名称等。
public synchronized Set<Integer> activeVms() {/** This method is synchronized because the Matcher object used by* fileFilter is not safe for concurrent use, and this method is* called by multiple threads. Before this method was synchronized,* we'd see strange file names being matched by the matcher.*/Set<Integer> jvmSet = new HashSet<Integer>();if (! tmpdir.isDirectory()) {return jvmSet;}if (userName == null) {/** get a list of all of the user temporary directories and* iterate over the list to find any files within those directories.*/File[] dirs = tmpdir.listFiles(userFilter);for (int i = 0 ; i < dirs.length; i ++) {if (!dirs[i].isDirectory()) {continue;}// get a list of files from the directoryFile[] files = dirs[i].listFiles(fileFilter);if (files != null) {for (int j = 0; j < files.length; j++) {if (files[j].isFile() && files[j].canRead()) {jvmSet.add(new Integer(PerfDataFile.getLocalVmId(files[j])));}}}}} else {/** Check if the user directory can be accessed. Any of these* conditions may have asynchronously changed between subsequent* calls to this method.*/// get the list of files from the specified user directoryFile[] files = tmpdir.listFiles(fileFilter);if (files != null) {for (int j = 0; j < files.length; j++) {if (files[j].isFile() && files[j].canRead()) {jvmSet.add(new Integer(PerfDataFile.getLocalVmId(files[j])));}}}}// look for any 1.4.1 filesFile[] files = tmpdir.listFiles(tmpFileFilter);if (files != null) {for (int j = 0; j < files.length; j++) {if (files[j].isFile() && files[j].canRead()) {jvmSet.add(new Integer(PerfDataFile.getLocalVmId(files[j])));}}}return jvmSet;}}