如果 linux 中的任何 PID 超过特定限制,如何发出警报?

How to throw an alert if any PID in linux goes above a certain limit?

我想制作一个 运行 在后台运行并且不占用大量内存的进程监视器。我将通过 SSH 登录到远程计算机,如果可能的话,我想 运行 我本地计算机上的脚本。当任何 运行ning 进程超过 CPU 和 MEM 的预定义限制时,我需要它发出警报(声音?)。

有什么方法可以从 'top' 获取值吗?我尝试了几个 'ps' 命令,但运气不佳..

ps 应该给你 cpu 和 pid 的内存使用情况。

ps -p <pid> -o %cpu,%mem

结果:

%CPU %MEM
12.9  0.9

让你继续前进的东西。如果 CPU 限制高于 50% 且 MEM 限制高于 20%,此脚本 (test.bash) 将抛出一条消息。它以 pid 作为参数。

#!/bin/bash                                                                                                                                                                                                                           

pid=
clim=50
mlim=20
ps -p $pid -o %cpu,%mem | grep "^[0-9].*" > /tmp/test.txt

while read cpu mem
do
    if [ $(bc <<< "$cpu > $clim") == 1 ]; then
        echo "CPU ($cpu) is above limit for PID:$pid"
    fi
    if [ $(bc <<< "$mem > $mlim") == 1 ]; then
        echo "MEM ($mem) is above limit for PID:$pid"
    fi
done < /tmp/test.txt

运行 脚本:

]$ ./test.bash 1918
CPU (50.2) is above limit for PID:1918
MEM (20.1) is above limit for PID:1918

这是我拼凑的剧本。希望有人觉得这很有用。您可以更改顶部的 max_percent 变量以满足您的需要。 sleeper 变量是循环执行的时间间隔(以秒为单位)。

#!/bin/bash
# alarm.sh
max_percent=94
sleeper=1
frequency=1000
duration=300

# To enable the script:
# chmod u+x alert.sh

# get the total available memory:
function total_memory {
    echo "Total memory available: "
    TOTAL_MEM=$(grep MemTotal /proc/meminfo | awk '{print }')
    #Another way of doing that:
    #total_mem=$(awk '/MemTotal/ {print }' /proc/meminfo)
    echo "---------- $TOTAL_MEM ---------------"
}


# alarm function params: frequency, duration
# Example:
# _alarm 400 200
_alarm() {
  ( \speaker-test --frequency  --test sine )&
  pid=$!
  \sleep 0.s
  \kill -9 $pid
}

function total_available_memory {
    total_available_mem=$(</proc/meminfo grep MemTotal | grep -Eo '[0-9]+')
    total_free_mem=$(</proc/meminfo grep MemFree | grep -Eo '[0-9]+')
    total_used_mem=$((total_available_mem - total_free_mem))
    #percent_used=$((total_available_mem / total_free_mem))
    # print the free memory
    # customize the unit based on the format of your /proc/meminfo
    percent_used=$(printf '%i %i' $total_used_mem $total_available_mem | awk '{ pc=100*/; i=int(pc); print (pc-i<0.5)?i:i+1 }')

    if [ $percent_used -gt $max_percent ]; then
        echo "TOO MUCH MEMORY IS BEIGN USED!!!!!!!! KILL IT!"
        _alarm $frequency $duration
    fi

    echo "Available: $total_available_mem kb  -  Used: $total_used_mem kb  -  Free: $total_free_mem kb  -  Percent Used: $percent_used %"

}

# RUN THE FUNCTIONS IN AN INFINITE LOOP:
# total_memory

echo "Press [CTRL+C] to stop.."
while :
do
    total_available_memory
    sleep $sleeper
done