等待并行批处理脚本或命令行

时间:2017-06-20 11:14:14

标签: batch-file cmd parallel-processing

我发现很难在这里修改脚本以满足我的要求: https://stackoverflow.com/a/12665498/4683898

@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

我正在使用批处理脚本,而不是执行进一步的批处理脚本,而是简单地并行执行cmd命令(运行一段时间),并且可以正常使用上述脚本。

但是,我希望能够一次运行多于2个命令/脚本,即3个,4个,5个(或任何我想要的)命令,并行运行,让我们称之为x。

所以,我想运行x个cmd命令(在并行中执行),等待它们终止(使用/ c),然后执行 next 一堆x cmd命令,然后是 next 一堆等,直到所有cmd命令都执行完毕。

我如何相应地修改该脚本? (我已经做了一些尝试,虽然重复错误“进程无法访问该文件,因为它正被另一个进程使用。”在启动批处理脚本中;我认为这个'文件'是指锁文件。)

由于

编辑:

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

call :a start cmd.exe /c somecommandA 1
call :a start cmd.exe /c somecommandB 2
call :wait
call :a start cmd.exe /c somecommandC 1
call :a start cmd.exe /c somecommandD 2
call :a start cmd.exe /c somecommandE 3

exit /b
:a
start "%~2" cmd /c 9>"%lock%%2" %1
exit /b
:wait
1>nul 2>nul ping /n 2 ::1
for %%N in (%lock%*) do (
  ( rem
  ) 9>"%%N" || goto :Wait
) 2>nul

2 个答案:

答案 0 :(得分:1)

您可以使用此脚本轻松调用文件:

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


call :a one.bat 1
call :a two.bat 2
call :wait
call :a three.bat 1
call :a name.bat 2
call :a gfwagwa.bat 3


exit /b
:a
start "%~2" cmd /c 9>"%lock%%2" %1
exit /b
:wait
1>nul 2>nul ping /n 2 ::1
for %%N in (%lock%*) do (
  ( rem
  ) 9>"%%N" || goto :Wait
) 2>nul

call :wait只是取代等待。每当您调用要异步运行的所有文件时,请调用wait函数。然后你可以调用更多的脚本。

第二个参数是锁定文件的编号。在使用它们的所有脚本关闭之前(即在下一个call :wait之前),确保您没有重复的数字。虽然你无论如何都不会用完数字,但没有理由使用重复数据。

答案 1 :(得分:0)

只是提供另一种方式:

@ECHO off
start "MyCommand-%~n0" cmd.exe /c ping localhost
start "MyCommand-%~n0" cmd.exe /c ipconfig /all
start "MyCommand-%~n0" cmd.exe /c sysinfo
:loop
tasklist /fi "windowtitle eq MyCommand-%~n0"  | find "===" >nul && goto :loop
echo finished!

修改以征求您的意见。 bunch是并行运行的命令数。

@ECHO off
setlocal enabledelayedexpansion
set bunch=3

for /f "delims=:" %%a in ('findstr /n /b "REM ==" %~f0') do set /a datastart=%%a+1
set count=0
for /f "skip=%datastart% usebackq delims=" %%a in ("%~f0") do (
  set /a "count=(count+1) %% %bunch%"
  echo starting: %%a
  start "MyCommand-%~n0" cmd.exe /c %%a
  if !count!==0 echo waiting & call :loop
)
echo waiting & call :loop
echo finished!
goto :eof

:loop
tasklist /fi "windowtitle eq MyCommand-%~n0"  | find "===" >nul && goto :loop
goto :eof

REM == START DATA ==
ping localhost
ipconfig /all
systeminfo
tasklist
echo hello
schtasks /query
wmic bios get /value
timeout 10

第一个for只获取命令所在的行号(DATA部分的开头)