1

In bash there is a option to wait for all the background process started by current shell using wait command.

e.g.

#!/bin/bash
{ sleep 5; echo "waking up after 5 seconds"; } &
{ sleep 1; echo "waking up after 1 second"; } &
wait
echo all jobs are done!

How do I do same in Windows batch script? I have to run multiple commands in background and wait till all finishes.

3
  • there is no simple way of doing that in cmd I know of (if you want to run your jobs in parallel), but if you could use Powershell there is an equivalent called wait-job (technet.microsoft.com/en-us/library/Hh849735.aspx)
    – wmz
    Commented Aug 18, 2015 at 7:35
  • Powershell is not allowed :(
    – Hemant
    Commented Aug 20, 2015 at 6:58
  • Just out of curiosity, what's the reasoning behind that [PS is not allowed]?
    – wmz
    Commented Aug 20, 2015 at 7:54

1 Answer 1

3

You will probably want the START command to initiate parallel processing, though it could be done via WMIC. Note that the first argument is treated as a window title if it is quoted. That is why my first argument is an empty string. The /B option runs the command in the same window. Remove it if you want a new window for each command.

There is no simple native batch command or option to wait for a series of parallel processes to finish.

I like to redirect an unused file handle to a file for each process, thus establishing an exclusive lock. I can then detect if a process is still running by attempting to redirect (CALL ) (effectively a null op) to the same lock file. If the redirection fails, then the process is still running. Success indicates the process has terminated.

The test must be done against each of the lock files in a polling loop. Adding a delay is a good idea to prevent the polling loop from abusing resources.

@echo off
set "lock=%temp%\%~nx0.lock"
start "" /b "timeout" 5 9>"%lock%.1"
start "" /b "timeout" 8 9>"%lock%.2"
:wait
timeout 1 /nobreak >nul
2>nul (for %%F in ("%lock%.*") do 9>"%%F" (call ) && del "%%F" || goto :wait)
echo OK

If you have a large number of parallel processes to run, and you want to limit the number of simultaneous processes, then you may be interested in https://stackoverflow.com/a/11715437/1012053

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .