tags:

views:

323

answers:

1

I have a synchronization problem in java. I want my main thread to wait until process "p1" is finished. I have used "waitfor" method. it has not worked for me.

Process p1 = runtime.exec("cmd /c start /MIN " + path + "aBatchFile.bat" );
p1.waitFor();

Could anybody help me please?

Thank you so much.

+4  A: 

The problem here is that the Process object you get back from exec() represents the instance of cmd.exe that you start. Your instance of cmd.exe does one thing: it starts a batch file and then exits (without waiting for the batch file, because that's what the start command does). At that point, your waitFor() returns.

To avoid this problem, you should be able to run the batch file directly:

Process p1 = runtime.exec(path + "aBatchFile.bat");
p1.waitFor();

Alternately, try the /wait command line option:

Process p1 = runtime.exec("cmd /c start /wait /MIN " + path + "aBatchFile.bat" ); 
p1.waitFor(); 
Greg Hewgill
yes - also I think removing start should make you wait as well.
Fakrudeen
Thanks for your answer.putting /wait does not work for me again. It does not wait the main thread.if I remove "start" or if I remove "cmd /c start /wait /MIN ", the process p1 is not run at all.I checked them. Could you help me?Thanks.
Shadi
@Shadi: And what happens if you remove "start /MIN" so your command is `exec("cmd /c " + path + "aBatchFile.bat")`?
Greg Hewgill
again P1 is not run :(
Shadi
@Shadi: I suggest you avoid the use of batch files.
Greg Hewgill
However, If I do not use batch file, and for example, I want to call an "exe" file, I need to pause my main thread until the execution of the "exe" file is finished. So, how can I do that?
Shadi
@Shadi: Exactly as you originally wrote in your question (except don't use `cmd`). Just run your executable directly.
Greg Hewgill