【问题标题】:Java: wait for exec process till it exitsJava:等待exec进程直到它退出
【发布时间】:2012-09-16 17:06:14
【问题描述】:

我正在 Windows 中运行一个从 Windows 事件中收集日志的 java 程序。将创建一个 .csv 文件,在该文件上执行某些操作。

命令被执行和管道化。如何让我的 Java 程序等待进程完成?

这是我正在使用的代码 sn-p:

Runtime commandPrompt = Runtime.getRuntime();
try {           
    Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable @{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 ';  ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
//I have tried waitFor() here but that does not seem to work, required command is executed but is still blocked
} catch (IOException e) { }
// Remaining code should get executed only after above is completed.

【问题讨论】:

标签: java process exec


【解决方案1】:

您需要使用waitFor() 而不是wait()。这样你的线程就会阻塞,直到执行的命令完成。

【讨论】:

  • 不,这不是我上面提到的解决方案,waitfor() 在 cmets 中不起作用。如果成功了就没有问题了
【解决方案2】:

我在这里找到了答案Run shell script from Java Synchronously

public static void executeScript(String script) {
    try {
        ProcessBuilder pb = new ProcessBuilder(script);
        Process p = pb.start(); // Start the process.
        p.waitFor(); // Wait for the process to finish.
        System.out.println("Script executed successfully");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【讨论】:

    【解决方案3】:

    这应该有效。如果不是,请说明究竟是什么不起作用

    Runtime commandPrompt = Runtime.getRuntime();
    try {           
        Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable @{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 ';  ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
        powershell.waitFor();
    } catch (IOException e) { }
    // remaining code
    

    【讨论】:

    • 其实我已经试过了。该命令将给出一个 CSV 文件作为输出,但其余代码在创建 CSV 之前开始执行。我相信这可能是因为命令中使用了管道。
    • 这是一种竞争条件。您不能依赖缓冲缓存文件系统上的文件创建。如果你的下一个代码依赖于这个文件,你可以把它保存在内存中,或者轮询文件系统。 (Linux 有 select/epoll )
    • 是的,如果创建了文件,我已经通过轮询进行了临时修复。是的,在创建文件时存在竞争条件。
    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多