efficient way to keep checking if a program is still running with a batch script

北战南征 提交于 2019-12-11 17:04:28

问题


I would like to write a batch script, and part of the script I want to check if program1.exe is still running. Once program1.exe is no longer running, I want to do something.

I can write a while loop to do this, but it will keep checking over and over and use up 100% of one of my cores in my CPU.

Is there an efficient way to check? Maybe a hack that checks this condition once a second?

Thanks


回答1:


Try like this :

@echo off
Set "MyProcess=Notepad.exe"

:start
tasklist | find /i "%MyProcess%">nul && goto:wait || start %MyProcess%
goto:start

:wait
ping localhost -n 3 >nul
goto:start

Just replace Notepad.exe with the name of your program




回答2:


Is there an efficient way to check? Maybe a hack that checks this condition once a second?

Use the timeout /t 1 command. If you don't want the "Waiting for 1 seconds, press a key to continue ..." message to appear, use timeout /t 1 > nul.




回答3:


you can use a for /f loop with a tasklist to check for the process with a 1 sec timeout using the ping command (you can also use timeout /t 1 >nul instead). The following example is from one of my scripts:

:CMBK
ping -a -n 1 127.0.0.1 1>2>nul
FOR /F "tokens=1,2,3 delims=: " %%A IN ('tasklist /fi "imagename eq program1.exe" /fo list') do set imgnm=%%A
if not '%imgnm%'=='INFO' goto cmbk


来源:https://stackoverflow.com/questions/25575532/efficient-way-to-keep-checking-if-a-program-is-still-running-with-a-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!