I have a master batch
file which calls another list batch
files. I want to wait until all the batch
files are executed (cannot say which one will execute faster) and comes to master batch
file to execute the remaining.
Example:
a) master.bat b) build.bat
call build.bat start web.bat
post.bat start db.bat
here master.bat
calls a file build.bat
and build.bat
files runs the web & db bat
files in parallel and once they are executed, it has to return to master.bat
and run the post.bat
.
can any one please guide me how to do this.
Finally got the resolution but forgot to update :)
@echo off
setlocal
set "lock=%temp%\wait%random%.lock"
:: Launch processes asynchronously, with stream 9 redirected to a lock file.
:: The lock file will remain locked until the script ends.
start "" 9>"%lock%1" web.bat
start "" 9>"%lock%2" db.bat
:Wait for both processes to finish (wait until lock files are no longer locked)
1>nul 2>nul ping /n 2 ::1
for %%N in (1 2) do (
(call ) 9>"%lock%%%N" || goto :Wait
) 2>nul
::delete the lock files
del "%lock%*"
:: Finish up
echo Done - ready to continue processing.
Thanks,
If you don't mind using an additional tool – the Windows command processor doesn't support this "out of the box" – you can do it like this without the need for "busy waiting" or using "lock" files:
mparallel.exe --count=3 --shell first.bat : second.bat : third.bat
call post.bat
First line will start first.bat
, second.bat
and third.bat
in parallel. It will not return until all three have terminated. We use --shell
here to run tasks in a shell, which is required for BAT files. After the three BAT's have completed, post.bat
is executed. Could be another mparallel call though.
Within master.bat:
:flagfloop
set "flagfile=%temp%\%random%%random%%random%"
if exist "%flagfile%*" goto flagfloop
call build
:wbuild
if exist "%flagfile%*" timeout /t 10 >nul&goto wbuild
post.bat
Within build.bat
for %%i in (web db) do (
echo.>"%flagfile%%%i"
start %%i.bat
)
Within web.bat and db.bat, just before the batch exits,
del "%flagfile%%%~n0" >nul 2>nul
Which should select a random tempfile-prefix; create the files 123321123web and 123321123db for the duration of the third-level .bat
s and then proceed with the main routine when both have finished (The timeout is set to 10 sec; your option to change this as necessary)
This question is a duplicated of Wait For Commands to Finish
You may use several flag files, one per running Batch file. Master Batch file may create Flagfile.1 when enter, and the called Batch file may delete it before end.
The master Batch file just must wait for all flagfiles disappear. For example, in master file:
echo X > flagfile.1
start build.bat 1 arg1
echo X > flagfile.2
start build.bat 2 arg2
.....
:wait
if exist flagfile.* goto wait
post.bat
In any build.bat Batch file:
echo Do my process...
del flagfile.%1
exit /B
Use CALL command as below:
master.bat :
call build.bat
call post.bat