Home > Software design >  automatically stop when a process ends in batch script
automatically stop when a process ends in batch script

Time:10-01

I want to limit the running time for exec.exe to 60 seconds but if exec.exe ends before the timeout will stop automatically. I have tried from various sources but to no avail, I hope anyone can help me. Thanks for all your help.

My batch scripts:

@echo off
start S:\sys_\sys_e\exec.exe
timeout /t 60
taskkill /im exec.exe
exit /b 0

CodePudding user response:

You can simply test the process every second to see if it is still running, if it is not stop the timeout and exit.

@echo off & set cnt=
start "" "S:\sys_\sys_e\exec.exe"
:count
(timeout /t 1)>nul
set /a cnt =1
if %cnt% lss 60 (
   tasklist /FI "IMAGENAME eq exec.exe" | findstr "exec" >nul && goto :count || exit /b 0
) else (
   taskkill /IM "exec.exe"
)

Explanation: We're doing a simple arithmetic addition by one each time we goto the label :count. We test the count each time to ensure it is not yet 60 seconds, if not, we test if the process is still running using tasklist and piping it to findstr so we are able to use errorlevel

The conditional operators && is saying, if the exit code of the previous command is true, issue the command after && which simply goes back to the label. Then || becomes the or operator, meaning if the condition is false, run the preceding command, which in this case is exit. So should the executable have by stopped, we will detect it and simply stop the script. However, if the executable is still active ny the time out %cnt% variable has reached a count of 60 we will kill it.

  • Related