为什么以下批处理代码可能会退出?

时间:2019-12-08 14:40:03

标签: batch-file

我正在使用该批处理自动重新启动某些程序,它们运行得很好,但是有时该批处理退出,这导致process_1和process_2也退出。似乎一切正常,但是批处理本身崩溃了。为什么?

@echo off

cd %~dp0

set process_1=process_1.exe
set process_2=process_2.exe
set interval=10

:check_service 

tasklist > task_tmp.txt

findstr %process1% task_tmp.txt> NUL
if ErrorLevel 1 (
    timeout /t 1 /nobreak > NUL 
    goto start_1
)

findstr %process2% task_tmp.txt> NUL
if ErrorLevel 1 (
    timeout /t 1 /nobreak > NUL 
    goto start_2
)


timeout /t %interval% /nobreak > NUL
goto check_service

:start_1

start /b "" %process_1%
echo %date% %time% %process_1%  " down, up it" >>  start_note.txt
goto check_service 

:start_2

start /b ""  %process_2%
echo %date% %time% %process_2%  " down, up it" >>  start_note.txt
goto check_service 


2 个答案:

答案 0 :(得分:1)

您可以这样简化:

@echo off
Set "MyProcess1=process_1.exe"
Set "MyProcess2=process_2.exe"

:check
%SystemRoot%\System32\tasklist.exe /NH | %SystemRoot%\System32\find.exe /i "%MyProcess1%">nul || echo starting %MyProcess1% && start "process 1" "%MyProcess1%"
%SystemRoot%\System32\tasklist.exe /NH | %SystemRoot%\System32\find.exe /i "%MyProcess2%">nul || echo starting %MyProcess2% && start "Process 2" "%MyProcess2%"
%SystemRoot%\System32\timeout.exe /t 10 /nobreak >nul
goto check

命令tasklistfindtimeout使用完全限定的文件名,以使此批处理文件独立于 local 环境变量的值PATHPATHEXT,并避免Windows命令处理器必须搜索这三个可执行文件。

答案 1 :(得分:0)

您可以像这样缩短代码:

@echo off
pushd "%~dp0"
:chkservice
tasklist | find /I "Process_1.exe" >nul 2>&1
if errorlevel 1 (
  start Process_1.exe  
  echo %date% %time% Process_1.exe Down up, it >>startnote.txt
)
tasklist | find /I "Process_2.exe" >nul 2>&1
if errorlevel 1 (
  start Process_2.exe  
  echo %date% %time% Process_2.exe Down up, it >>startnote.txt
)
timeout /t 10 /nobreak >nul 2>&1
goto chkservice