Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for batch-end

I have 4 lines in my bat file, but my thread goes on before the cmd closes.

Here's my code:

rt = Runtime.getRuntime();
proc = rt.exec("cmd /c start C:\\temp\\test.bat");
if(proc.waitFor() == 0) {
    return "did it";
} else {
    return "nooope";
} 

I always get the did it before cmd closes. Here is my batch-file:

@ECHO off
taskkill /IM "Process.exe" /F
cd "C:\Program Files\ProcessFolder"
START /WAIT Process.exe
START otherProcess.exe
EXIT

any help?

like image 539
Markus Avatar asked May 30 '26 09:05

Markus


1 Answers

The problem is that you're using start - which will start a new shell in which to run the batch file. The original shell then closes, so the process terminates, and your Java program continues.

Remove the start and it should work, in terms of waiting for the batch file to end. However, you've then got the same problem again within the batch file when you start otherProcess.

Either don't use start, or always use start /wait within the batch file.

If you use start /wait within the Java code, however, you'll end up with a command prompt sitting there at the end of the batch file execution, as far as I can tell by experimentation.

like image 178
Jon Skeet Avatar answered May 31 '26 23:05

Jon Skeet