下面是显示如何,当它被另一个进程写入读取的文件的例子。这与jeb显示非常相似,只是我添加了一个通用测试来查看过程是否完成。它假定进程在整个执行过程中保持对文件的锁定,并且还假定20个连续的空行表示文件结束,否则我们正在等待进程的更多输出。 20空行阈值可以设置为适合您的任何数字。
如果该过程将部分行写入文件,此解决方案可能无法正常工作。如果这个过程总是在单一操作中完成每行的完整写入,我相信这是可靠的。此外,这些行必须小于或等于1021个字节长,并且它们必须通过回车符,换行符来终止。
@echo off
setlocal enableDelayedExpansion
set "file=test.txt"
set emptyCount=0
del "%file%
:: For this test, I will start an asynchronous process in a new window that
:: writes a directory listing to an output file 3 times, with a 5 second pause
:: between each listing.
start "" cmd /c "(for /l %%N in (1 1 3) do @dir & ping localhost -n 6 >nul) >"%file%""
:wait for the output file to be created and locked
if not exist "%file%" goto :wait
:: Now read and process the file, as it is being written.
call :read <"%file%"
exit /b
:read
set "ln="
set /p "ln="
if defined ln (
REM Process non-empty line here - test if correct line, extract size, and add
REM I will simply echo the line instead
echo(!ln!
REM Reset emptyCount for end of file test and read next line
set /a emptyCount=0
goto :read
) else (REM End of file test
REM Count how many consecutive empty lines have been read.
set /a emptyCount+=1
REM Assume that 20 consecutive empty lines signifies either end of file
REM or else waiting for output. If haven't reached 20 consectutive
REM empty lines, then read next line.
if !emptyCount! lss 20 goto :read
REM Test if output file is still locked by attempting to redirect an unused
REM stream to the file in append mode. If the redirect fails, then the file
REM is still locked, meaning we are waiting for the process to finish and have
REM not reached the end. So wait 1 sec so as not to consume 100% of CPU, then
REM reset count and try to read the next line again.
REM If the file is not locked, then we are finished, so simply fall through
REM and exit.
(echo off 9>>"%file%")2>nul || (
set emptyCount=0
ping localhost -n 2 >nul
goto :read
)
)
exit /b
不可能从批处理文件AFAIK。如果你可以将rsync工具的输出重定向到批处理文件,那么它应该是可行的。 – Jon 2013-02-12 09:53:36
我会使用'tail -v' from cygwin – 2013-02-12 09:54:54
@Jon我已经使用批处理脚本,在另一个cmd窗口中启动rsync,并且rsync输出被重定向到一个txt文件。在我的批处理脚本中,在启动rsync的下一行中,我想读取txt文件并计算复制的数据量。原因是因为我已经有了文件夹的总大小(大约4GB),并且我想在控制台输出上写入多少日期将被复制。可能吗? – 2013-02-12 10:21:33