windows 等待命令完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6946535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wait For Commands to Finish
提问by anderson
I have a Windows batch file that starts other batch files. How do I wait for all the other batch files to finish before executing somthing in the first batch? I can't use /wait because I need the other commands to run in parallel.
我有一个启动其他批处理文件的 Windows 批处理文件。在第一批中执行某些内容之前,如何等待所有其他批处理文件完成?我不能使用 /wait,因为我需要其他命令并行运行。
回答by Aacini
You may use several flag files, one per running Batch file. For example:
您可以使用多个标志文件,每个运行的批处理文件一个。例如:
First batch file create Flagfile.1 when enter, and delete it before end, and the same way the rest of concurrent batch files (Flagfile.2,...)
第一个批处理文件在输入时创建Flagfile.1,并在结束前删除它,其余并发批处理文件(Flagfile.2,...)的方式相同
The main file just must wait for all flagfiles disappear. For example, in Main file:
主文件必须等待所有标志文件消失。例如,在主文件中:
start Batch1
start Batch2
.....
:wait
if exist flagfile.* goto wait
In any Batch file, for example Batch1:
在任何批处理文件中,例如 Batch1:
echo %time% > flagfile.1
echo Do my process...
del flagfile.1
exit
回答by woohoo
My suggestion is to use CALL
command. An example from Batch Files:
我的建议是使用CALL
命令。批处理文件中的一个示例:
Batch1.bat listing:
Batch1.bat 列表:
REM Batch1.bat
SET ABC=1
CALL BATCH2.BAT %ABC%
ECHO ABC = %ABC%
BATCH2.BAT %ABC%
ECHO ABC = %ABC%
where Batch2.bat listing is:
其中 Batch2.bat 列表是:
REM Batch2.bat
SET ABC=%ABC%%1
EDIT:编辑:根据@Andriy M 的反馈,这里是两个批次的改进版本:
Batch 1:
第 1 批:
@ECHO OFF
REM Batch1.bat
SET ABC=1
CALL batch2.bat %ABC%
ECHO 1. ABC = %ABC%
CALL batch2.bat %ABC% REM test this line with CALL and without
ECHO 2. ABC = %ABC%
Batch 2:
第 2 批:
@ECHO OFF
REM Batch2.bat
SET tmout=5
echo sleeping %tmout% seconds...
REM this introduces a timeout by using a nonexistent ip address
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
echo done sleeping
SET ABC=%ABC%%1
See the line in batch1 where I wrote the comment test this line with CALL and without. Run that batch twice, with that line having CALL
and without CALL
.
请参阅 batch1 中的行,其中我使用 CALL 和不使用. 运行该批次两次,该行有CALL
和没有CALL
.
The output from console withoutCALL
:
控制台的输出没有CALL
:
C:\temp>batch1.bat
sleeping 5 seconds...
done sleeping
1. ABC = 11
sleeping 5 seconds...
done sleeping
And now the output from console withCALL
:
而现在,从控制台输出有CALL
:
C:\temp>batch1.bat
sleeping 5 seconds...
done sleeping
1. ABC = 11
sleeping 5 seconds...
done sleeping
2. ABC = 1111
Please note the difference: we get the 2nd echo, q.e.d.
请注意不同之处:我们得到第二个回声,qed