如何解决实施超时的循环提示?

时间:2019-06-04 20:50:05

标签: batch-file cmd prompt

修改此处共享的代码以使其循环,但是在随后的迭代中,该代码每次都假定第一个输入。可能与延迟扩展有关,但我不知道如何解决?

@echo off
setlocal EnableDelayedExpansion

rem Execute a SET /P command with time out
rem Antonio Perez Ayala
rem Modified

rem If this file is re-executed as pipe's right side, go to it
if "%~1"=="TimeoutMonitor" goto %1

:Loop

del InputLine.txt 2> NUL
(
   set /P "input=You have 3 seconds to type yes or no: " > CON
   > InputLine.txt call set /P "=%%input%%" < NUL
) 2> NUL | "%~F0" TimeoutMonitor 3
set /P "input=" < InputLine.txt
del InputLine.txt
if /I "%input%"=="no" echo You typed no
if /I "%input%"=="yes" echo You typed yes
PING -n 3 127.0.0.1>nul

goto :Loop


:TimeoutMonitor

rem Get the PID of pipe's left side
tasklist /FI "IMAGENAME eq cmd.exe" /FO TABLE /NH > tasklist.txt
for /F "tokens=2" %%a in (tasklist.txt) do (
   set "leftSidePipePID=!lastButOnePID!"
   set "lastButOnePID=%%a"
)
del tasklist.txt

rem Wait for the input line, or until the number of seconds passed
for /L %%i in (1,1,%2) do (
   ping -n 2 localhost > NUL
   if exist InputLine.txt exit /B
)

rem Timed out: kill the SET /P process and create a standard input line
taskkill /PID %leftSidePipePID% /F > NUL
echo/
echo Timed Out> InputLine.txt

exit /B

样本输入和输出:

You have 3 seconds to type yes or no: yes
You typed yes
You have 3 seconds to type yes or no: no
You typed yes

0 个答案:

没有答案