This is a followup question to my other question : Run bat file in Java and wait
The reason i am posting this as a separate question is that the one i already asked
Start cmd with the /c switch instead of /k and get rid of the start:
Process p = Runtime.getRuntime().exec(
"cmd /c SQLScriptsToRun.bat" + " -UuserName -Ppassword"
+ " projectName");
/k tells cmd: “Run that command and then stay open”, while /c says “Run that command and then exit.”
/k is for interactive use where you want an initializing batch file and afterwards still use the console.
Your main problem here, however, is that you are creating yet another process by using start. To run a batch file this is totally unnecessary and prevents you from knowing when the batch was run completely, since Java has a reference to the original cmd process you started, not the one you spawned with start.
In principle, this now looks like the following:
cmd and instructs it to run start foo.bat and stay open for interactive input (/k)Java memorizes the process ID (PID 42) to later reference that process
cmd (PID 42) startscmd (PID 42) runs start foo.batstart foo.bat launches another instance of cmd, since that's what should happen to run batch files
cmd (PID 57005) startscmd (PID 57005) runs foo.batcmd (PID 57005) exits (This marks the event you'd like to know about)cmd (PID 42) shows the prompt and obediently waits for input (unbeknownst to them the prompt is never seen by a user and no input will ever come ... but cmd (PID 42) waits ...)Java likes to know whether the process is finished and checks PID 42
What you want (and what above change will do) is:
cmd and instructs it to run foo.bat and close after running the command (/c)Java memorizes the process ID (PID 42) to later reference that process
cmd (PID 42) startscmd (PID 42) runs foo.batcmd (PID 42) exitsJava likes to know whether the process is finished and checks PID 42