等待并行批处理脚本

sud*_*r m 14 parallel-processing batch-file

我有4个批处理文件.我想运行one.bat,并two.bat在一次,兼任.这两个批处理文件完成后,three.batfour.bat应同时运行,在并行.我试过很多方法,但mot工作得很好.

任何人都可以帮助我吗?

dbe*_*ham 15

使用我提供的用于并行执行shell进程的简化版本的解决方案可以轻松完成此操作.有关文件锁定如何工作的说明,请参阅该解决方案.

@echo off
setlocal
set "lock=%temp%\wait%random%.lock"

:: Launch one and two asynchronously, with stream 9 redirected to a lock file.
:: The lock file will remain locked until the script ends.
start "" cmd /c 9>"%lock%1" one.bat
start "" cmd /c 9>"%lock%2" two.bat

:Wait for both scripts to finish (wait until lock files are no longer locked)
1>nul 2>nul ping /n 2 ::1
for %%N in (1 2) do (
  ( rem
  ) 9>"%lock%%%N" || goto :Wait
) 2>nul

::delete the lock files
del "%lock%*"

:: Launch three and four asynchronously
start "" cmd /c three.bat
start "" cmd /c four.bat
Run Code Online (Sandbox Code Playgroud)

  • @LưuVĩnhPhúc - 当然,你可能也想投入`/ nobreak`选项.但是,TIME不适用于XP,并且在撰写此答案时具有显着的市场份额.值得庆幸的是,由于不再支持XP,XP变得越来越不普遍. (3认同)
  • 等待你可以使用[`1> nul 2> nul timeout 1`而不是ping](http://stackoverflow.com/q/1672338/995714) (2认同)

小智 6

I had this same dilemma. Here's the way I solved this issue. I used the Tasklist command to monitor whether the process is still running or not:

:Loop
tasklist /fi "IMAGENAME eq <AAA>" /fi "Windowtitle eq <BBB>"|findstr /i /C:"<CCC>" >nul && (
timeout /t 3
GOTO :Loop
)
echo one.bat has stopped
pause
Run Code Online (Sandbox Code Playgroud)

You'll need to tweak the

<AAA>, <BBB>, <CCC>

脚本中的值,以便正确过滤您的过程.

希望有所帮助.


Ale*_*gna 3

创建一个启动 one.bat 和two.bat 的 master.bat 文件。当 one.bat 和 Two.bat 正确结束时,它们会回显到已完成的文件

if errorlevel 0 echo ok>c:\temp\OKONE
if errorlevel 0 echo ok>c:\temp\OKTWO
Run Code Online (Sandbox Code Playgroud)

然后master.bat等待两个文件的存在

del c:\temp\OKONE
del c:\temp\OKTWO
start one.bat
start two.bat
:waitloop
if not exist c:\temp\OKONE (
    sleep 5
    goto waitloop
    )
if not exist c:\temp\OKTWO (
    sleep 5
    goto waitloop
    )
start three.bat
start four.bat
Run Code Online (Sandbox Code Playgroud)

另一种方法是尝试使用 /WAIT 标志

start /WAIT one.bat
start /WAIT two.bat
Run Code Online (Sandbox Code Playgroud)

但你无法控制错误。

这是一些参考资料

http://malektips.com/xp_dos_0002.html

http://ss64.com/nt/sleep.html

http://ss64.com/nt/start.html

  • `start /WAIT xxx` 等待 xxx 完成,然后再让执行传递到批处理文件中的下一行。因此,“one.bat”必须在“two.bat”开始之前完成。您可以假设“one.bat”总是先完成并使用“start /wait Two.bat”,但这是一个假设。顺便说一句,你不必“启动 four.bat”,你可以只“调用 four.bat”(或者如果执行“four.bat”后没有其他事情要做,甚至可以放弃“call”)并且保存启动另一个命令处理器将使用的内存。 (4认同)