使用java检查应用程序是否正在运行?

Bhu*_*anK 4 java windows process

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

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

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

要检查给定的应用程序是否正在运行,我使用以下代码[参考链接]:

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;
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

但上面的代码对所有应用程序都返回 0。

提前致谢。

sea*_*ges 6

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

jps -l
19109 sun.tools.jps.Jps
15031 org.jboss.Main
14040 
14716
Run Code Online (Sandbox Code Playgroud)

Runtime.getRuntime().exec()您可以使用并读取输入流从该程序中抓取列表,然后在 Java 中搜索包名称以查找匹配项。

由于您想避免迭代所有结果,因此您可以使用 grep 结果来返回您正在查找的findstr基本结果: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
Run Code Online (Sandbox Code Playgroud)

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

Process p = Runtime.getRuntime().exec("jps -l | grep \"com.myapp.MyApp\"");
int exitVal = p.exitValue(); // Returns 0 if running, 1 if not
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)