下面是顯示如何,當它被另一個進程寫入讀取的文件的例子。這與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