繁体   English   中英

等待直到由Runtime.exec运行的进程退出(“ wmic进程调用创建notepad.exe”)

[英]Wait until process exit that run by Runtime.exec(“wmic process call create notepad.exe”)

我正在开发一个能够运行程序的应用程序,可以监视它们以在用户意外关闭它们并在注销时关闭程序的情况下重新打开。

我可以通过解析wmic process call create <program>的输入流来获取程序的进程ID。

我使用此代码段运行程序并检测用户何时关闭程序。 我的问题是我使用( wmic )运行程序的命令在运行它们后立即退出。

如何实现程序退出检测?

我的代码:

public static void main(String[] args) {
        Process process = null;
        try {
            process = Runtime.getRuntime()
                    .exec("wmic process call create \"notepad.exe\"");
            BufferedReader stdin = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            String processIdLine = "";
            String line;
            while ((line = stdin.readLine()) != null) {
                if (line.contains("ProcessId")) {
                    processIdLine = line;
                    break;
                }
                System.out.println(line);
            }
            stdin.close();
            String[] param = processIdLine.split("=");
            if (param.length > 1) {
                String pId = param[1];
                pId = pId.replaceAll(";", " ");
                pId = pId.replaceAll(" ", "");
                System.out.println("ID : " + pId);
            }
            try {
                process.waitFor();
              // I want it to hang here till notepad closed.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("PROCESSE EXIT");
        } catch (IOException e) {
            e.printStackTrace();
        }
}

注意:我不想使用tasklist命令并比较进程是否已退出

请查看ZeroTurnaroundZT-exec库,它为您提供了很多现成的功能:

try {
  new ProcessExecutor().command("java", "-version").exitValues(3).execute();
} catch (InvalidExitValueException e) {
  System.out.println("Process exited with " + e.getExitValue());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM