首页  编辑  

监控程序内存使用并在超过特定数值后自动重启进程

Tags: /计算机文档/脚本,批处理/   Date Created:
下面的代码可以监控进程内存(Private Bytes)使用,如果超过指定大小,就自动重启进程,需要第三方的pslist支持。
https://technet.microsoft.com/en-us/sysinternals/bb896649 
-------------------------
@echo off
if "%1"=="" goto help
if "%2"=="" goto help

:loop
REM tasklist /fi "memusage gt 2097152" /fi "imagename eq %1.exe" | find "%1.exe"
for /f "tokens=2,6" %%i in ('pslist -nobanner %1 ^|find "%1"') do (
if not "%%i" == "%1" (
      if %%j gtr %2 (
   echo %date% %time% Kill ^& Restart %1...
        taskkill /pid %%i /f
        start /b "" %1
 )
)
)

REM sleep 5 seconds
ping 127.0.0.1 -n 5 > nul  
goto loop

:help
echo Monitor restart process when process private bytes exceed specified value.
echo %~n0 [Exe file name] [KB SIZE]
echo Example: %~n0 mspaint 1024
echo     Kill ^& restart mspaint.exe when the Private Bytes more than 1MB
-------------------------
另外一种方法,利用tasklist(例如监控squid),监控物理内存使用:

@echo off
:loop
REM sleep 5 seconds
ping 127.0.0.1 -n 5 > nul
tasklist /fi "memusage gt 2097152" /fi "imagename eq squid.exe" | find "squid.exe"
if %errorlevel% == 0 (
  taskkill /im squid.exe /f
  squid.exe
)
goto loop

------------------