Java: wait for exec process till it exits

寵の児 提交于 2019-12-30 03:13:13

问题


I am running a java program in Windows that collects log from Windows events. A .csv file is created on which certain operations are to be performed.

The commands are execed and piped. How can I cause my Java program to wait until the process is finished?

Here is the code snippet I am using:

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.

回答1:


You need to use waitFor() instead of wait(). That way your thread will block until the executed command finishes.




回答2:


I found the answer here 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:


This shall work. If not, specify WHAT exactly does not work

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


来源:https://stackoverflow.com/questions/12448882/java-wait-for-exec-process-till-it-exits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!