要检查应用程序是否 运行 或不使用 java?

To check whether an application is running or not using java?

我有一个 java 应用程序在后台启动另一个 java 应用程序(第三方),所以在启动第三方后台应用程序之前我想检查该应用程序是否已经 运行宁与否(不想等待该应用程序终止)。
我正在使用以下代码启动第三方 java 应用程序:

String path = new java.io.File("do123-child.cmd").getCanonicalPath();
Runtime.getRuntime().exec(path);

注意:文件 "do123-child.cmd" 调用“.bat”文件到 运行 该应用程序。

要检查给定的应用程序是否 运行ning 我正在使用以下代码 [Ref link]:

boolean result = false;
try {
    String line;
    Process p = Runtime.getRuntime().exec("tasklist.exe");
    BufferedReader input =
            new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
        if(line.startsWith("myApp.exe")){
            result = true;
            break;
        }
     }
     input.close();
} catch (Exception err) {
     err.printStackTrace();
}
return result;

我想知道是否有其他方法可以在不迭代当前 运行ning 的所有进程的情况下执行此操作?喜欢:

Process p = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq myApp.exe\" /NH");
int exitVal = p.exitValue();
//if above code throw "java.lang.IllegalThreadStateException" means application is running.

但上面的代码 return 0 适用于所有应用程序。

提前致谢。

您可以使用 jps 检查 Java 个应用程序 运行。 jps 与 JRE 捆绑在一起。

jps -l
19109 sun.tools.jps.Jps
15031 org.jboss.Main
14040 
14716

您可以使用 Runtime.getRuntime().exec()reading the input stream 从该程序中抓取列表,然后在 Java.

中搜索匹配项的包名称

由于您想避免迭代所有结果,您可以使用 findstr 将结果 grep 到 return 您正在寻找的基本 p.exitValue() 结果:

Process p = Runtime.getRuntime().exec("jps -l | findstr /R /C:\"com.myapp.MyApp\"");
int exitVal = p.exitValue(); // Returns 0 if running, 1 if not

当然 findstr 是 Windows 特定的,因此您需要在 Mac:

上使用 grep
Process p = Runtime.getRuntime().exec("jps -l | grep \"com.myapp.MyApp\"");
int exitVal = p.exitValue(); // Returns 0 if running, 1 if not

jps 工具使用内部 API (MonitoredHost) 来获取此信息,因此您也可以完全在 Java 中完成此操作:

String processName = "com.myapp.MyApp";

boolean running = false;
HostIdentifier hostIdentifier = new HostIdentifier("local://localhost");

MonitoredHost monitoredHost;
monitoredHost = MonitoredHost.getMonitoredHost(hostIdentifier);

Set activeVms = monitoredHost.activeVms();
for (Object activeVmId : activeVms) {
    VmIdentifier vmIdentifier = new VmIdentifier("//" + String.valueOf(activeVmId) + "?mode=r");
        MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmIdentifier);
    if (monitoredVm != null) {
        String mainClass = MonitoredVmUtil.mainClass(monitoredVm, true);
        if (mainClass.toLowerCase().equals(processName.toLowerCase())) {
            running = true;
            break;
        }
    }
}

System.out.print(running);