veekxt
veekxt

Reputation: 370

Why does the following batch code may exit?

I am using this batch to automatically restart some program, they are running very well, but sometimes the batch exit, which causes process_1 and process_2 also exit. It seems that everything is normal, but the batch itself crashes. Why ?

@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 


Upvotes: 2

Views: 141

Answers (2)

SachaDee
SachaDee

Reputation: 9545

You can maybe simplify like this:

@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

Full qualified file names are used for the commands tasklist, find and timeout to make this batch file independent on the values of the local environment variables PATH and PATHEXT and to avoid that the Windows command processor has to search for these three executables.

Upvotes: 1

wasif
wasif

Reputation: 15488

You can shorten your code like this:

@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

Upvotes: 0

Related Questions