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

时间:2015-06-04 08:01:19

标签: java windows process

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

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

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

要检查给定的应用程序是否正在运行,我使用以下代码[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;

我想知道在没有迭代当前运行的所有进程的情况下是否还有其他方法可以做到这一点?喜欢:

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.

但是上面的代码为所有应用程序返回0 提前谢谢。

1 个答案:

答案 0 :(得分:4)

您可以使用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来查看结果,以返回您要查找的基本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);