等待通过调用批处理文件创建的进程完成

8

MyFile1.bat 调用了两次 MyFile2.bat:

start MyFile2.bat argA, argB, argC
start MyFile2.bat argX, argY, argZ

现在,我该如何等待通过调用 MyFile2.bat 生成的两个进程都完成?

4个回答

7

只需使用Start /WAIT参数即可。

start /wait MyFile2.bat argA, argB, argC
start /wait MyFile2.bat argX, argY, argZ

2
或者将 start 更改为 call,这是我的第一反应。然而,也许他们希望这两个调用并行运行。在这种情况下,你的建议和我的建议都不太合适。 - Andriy M

3
start /w cmd /c "start cmd /c MyFile2.bat argA, argB, argC & start cmd /c MyFile2.bat argA, argB, argCt"

根据我的测试,只要MyFile2.bat文件有效,这应该可以正常工作。最好使用完整的批处理文件路径。

3
您可以使用“状态文件”来了解状态,例如,在MyFile1.bat中执行以下操作:
echo X > activeProcess.argA
start MyFile2.bat argA, argB, argC
echo X > activeProcess.argX
start MyFile2.bat argX, argY, argZ
:waitForSpawned
if exist activeProcess.* goto waitForSpawned

在MyFile2.bat的结尾插入以下行:

del activeProcess.%1

您可以在等待周期中插入ping延迟,以便在此循环中浪费更少的CPU。

+1,但是为了确保没有权限问题,也许最好在%TEMP%目录中创建标志文件。我可能会在:waitForSpawned和条件之间添加一个小延迟,而且我会在脚本的开始处插入del行(顺便问一下,你是不是指del activeProcess.*?)以防万一脚本意外中断。 - Andriy M

2
您可以像这样做:
start MyFile2.bat argA, argB, argC
start MyFile2.bat argX, argY, argZ ^& echo.^>End.val ^& exit

:testEnd
if exist end.val (del end.val
                  echo Process completed
                  pause)
>nul PING localhost -n 2 -w 1000
goto:testEnd

当第二个start2.bat完成后,将创建一个名为“End.val”的文件,您只需要测试该文件是否存在,就可以知道您的进程已完成。
如果第一个myfile2执行时间较长,则可以使用另一个文件名重复上述操作,并在testend中进行更多测试。
 start MyFile2.bat argA, argB, argC ^& echo.^>End1.val ^& exit
 start MyFile2.bat argX, argY, argZ ^& echo.^>End.val ^& exit

:testEnd
if exist end.val if exist end1.val (del end.val
                                    del end1.val
                                    echo Process completed
                                    pause)
>nul PING localhost -n 2 -w 1000
goto:testEnd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接