如何检查批处理文件是否在Windows上运行?

时间:2014-02-19 18:57:01

标签: java windows batch-file runtime.exec

我正在Windows中运行一个进程。该过程由批处理文件“skrmedpostctl_start.bat”启动。我正在编写一个使用 skrmedpostctl 输出的java项目。我让系统在Linux平台上运行,但在Windows上运行。问题是在执行 skrmedpostctl (Linux中的shell脚本,Windows中的批处理文件)之前,我正在检查它是否已经运行。这就是我到目前为止所做的:

switch (CURRENT_OS) {
    case LINUX:
        String[] procCheck_SKR = new String[]{"/bin/bash", "-c",  "ps -ef | grep MedPost-SKR"};
        String[] procCheck_WSD = new String[]{"/bin/bash", "-c",  "ps -ef | grep WSD_Server"};
        try {
            String procs_SKR = systemCall(procCheck_SKR);
            String procs_WSD = systemCall(procCheck_WSD);
            if (procs_SKR.split("\n").length < 2)
                systemCall(new String[]{"/bin/bash", "-c", MM_BIN_DIR + "./skrmedpostctl start"});
            if (procs_WSD.split("\n").length < 2)
                systemCall(new String[]{"/bin/bash", "-c", MM_BIN_DIR + "./wsdserverctl  start"});
        } catch (IOException e) { e.printStackTrace(); System.exit(0); }
        break;
    case WINDOWS:
        String[] procCheck = new String[]{"cmd.exe", "/c", System.getenv("windir") +"\\system32\\tasklist.exe"};
        String pidInfo = "";
        try {
            Process proc = Runtime.getRuntime().exec(procCheck);
            BufferedReader reader = new BufferedReader(new InputStreamReader( proc.getInputStream() ) );
            for (String line; (line = reader.readLine()) != null; )
                pidInfo += line;
            reader.close();
        } catch (IOException e) { e.printStackTrace(); System.exit(0); }
        if (pidInfo.contains("NAME OF MY PROCESS")) {
            // do stuff
        }
        break;
    default: throw new IllegalArgumentException("Can't run this program on " + CURRENT_OS);
}

问题是当我运行批处理文件时,任务管理器只显示“Windows命令处理器”,而不是实际名称。所以,在linux中我可以做一个“ps -ef | grep ...”来检查它是否已经在运行,我似乎无法在Windows中做同样的事情。有没有办法做到这一点?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

tasklist /v

在详细模式(/v)中,tasklist返回窗口的标题。您可以在批处理文件中测试批处理文件的名称或特殊标题集。