Java:等待exec进程直到它退出
我在Windows中运行一个java程序,从Windows事件中收集日志。 创建一个.csv文件,在该文件上执行某些操作。
命令被执行和管道。 如何让我的Java程序等到进程完成?
这是我正在使用的代码片段:
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.
您需要使用waitFor()
而不是wait()
。 这样你的线程就会阻塞,直到执行的命令完成。
我在这里找到答案从Java Synchronously运行shell脚本
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(); } }
这应该工作。 如果没有,请指定什么不起作用
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