10

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.
Alan
  • 506
  • 7
  • 24
user1631171
  • 103
  • 1
  • 1
  • 9

3 Answers3

14

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

javabrett
  • 7,020
  • 4
  • 51
  • 73
dan
  • 13,132
  • 3
  • 38
  • 49
  • 1
    No that isnt the solution i have mentioned above that waitfor() does not work in the comments. If it worked then there would be no problem – user1631171 Sep 16 '12 at 17:16
7

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();
    }
}
Community
  • 1
  • 1
Lefteris
  • 111
  • 2
  • 6
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
tuergeist
  • 9,171
  • 3
  • 37
  • 58
  • Actually i have tried this. A CSV file is to be given as output by the command but rest of code starts executing before the CSV is created. I believe this may be because of the pipe used in the command. – user1631171 Sep 16 '12 at 17:21
  • It's a kind of a race condition. You cannot rely on file creation on buffered cached file systems. If your next code relies on this file, you can either keep it in memory instead or poll the filesystem for it. (Linux has select/epoll for that) – tuergeist Sep 17 '12 at 07:54
  • Yes i have made a temporary fix by polling if file is created. And yes there is a race condition when the file is being created. – user1631171 Sep 17 '12 at 12:39