热得到java中所有java运行进程的PID?

时间:2016-05-13 16:15:58

标签: java windows process pid

我创建了以下代码来获取所有进程的PID。但似乎JRE不包含jps,我应该在每次使用此代码时安装JDK。有谁知道如何获取java中所有正在运行的PIDs进程的所有java而不是手动而不是我的解决方案?

rt.exec("cmd.exe /k \"C:\\Program Files\\Java\\jdk1.8.0_73\\bin\\jps.exe\"");
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line = null;

while (true) {
    if (bufferedreader.ready())
        line = bufferedreader.readLine();
    else
        break;
    if (line == null || line.equals(""))
        break;
    System.out.println(line);
}

1 个答案:

答案 0 :(得分:2)

如果要列出进程及其命令行,请在Windows中处理id,这是命令:

wmic process where "name='java.exe'" get ProcessID, CommandLine

这相当于" ps -ef | grep java"在Linux

参考:根据Hung Huynh

的博文改编的答案

输出示例:

CommandLine  ProcessId
java  Test   620

jps的输出示例:

2312 Jps
620 Test

响应更新:

要从Java应用程序中检索进程ID列表,假设您使用的是Oracle JDK / Open JDK ,因为它特定于Sun / Oracle,可以按照下一步完成:

// Checking for local Host, one can do for remote machine as well
MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
// Take all active VM's on Host, LocalHost here
Set<Integer> vmlist = new HashSet<>(local.activeVms());
for (Integer id : vmlist) {
    // 1234 - Specifies the Java Virtual Machine identified by lvmid 1234 
    // on an unnamed host. This string is transformed into the absolute 
    // form //1234, which must be resolved against a HostIdentifier.
    MonitoredVm vm = local.getMonitoredVm(new VmIdentifier(String.format("//%d", id)));
    // take care of class file and jar file both
    String processname = MonitoredVmUtil.mainClass(vm, true);
    System.out.printf("%d: %s%n", id, processname);
}

参考:根据Vaibhav Choudhary

的博文改编的答案

输出示例:

88083: com.intellij.rt.execution.application.AppMain
88082: org.jetbrains.jps.cmdline.Launcher
82789: org.jetbrains.idea.maven.server.RemoteMavenServer
87892: sun.tools.jconsole.JConsole