Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: wait for exec process till it exits

Tags:

java

process

exec

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.
like image 497
user1631171 Avatar asked Sep 16 '12 17:09

user1631171


People also ask

How to wait for a process to finish Java?

The waitFor() method of Process class is used to wait the currently executing thread until the process executed by the Process object has been completed. The method returns immediately when the subprocess has been terminated and if the subprocess is not terminated, the thread will be blocked.

What is process WaitFor ()?

WaitFor() Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. WaitFor(Int64, TimeUnit) Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, or the specified waiting time elapses.

What is ProcessBuilder in Java?

This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes.


1 Answers

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

like image 87
dan Avatar answered Sep 22 '22 19:09

dan