I want to write a bash script to listen for CPU resource usage. If there is a long time for high CPU consumption, the script will kill the relevant process. I refer to the qustion https://unix.stackexchange.com/questions/66786/bash-script-that-automatically-kills-processes-when-cpu-memory-usage-gets-too-hi on the stackexchange.

#!/usr/bin/bash
set -e
KILL_LIST=("/usr/share" "chrome" "home" "stephen")
MAX_CPU=100
while [ 1 ]; do
    #iterate for each process to check in list
    for PROCESS_TOCHECK in ${KILL_LIST[*]}; do
        ROW=$(top -bcSH -n 1 | grep $PROCESS_TOCHECK | sort -k 9 -r -n | head -n 1)
        #1108 gdm   39  19 4102900 192076 108840 S   0.0   2.4   0:00.00 /usr/bin/gnome-shell
        PID=$(echo $ROW|awk '{print $1}')
        CPU=$(echo $ROW|awk '{print $9}')
        NAME=$(echo $ROW|awk '{print $12}')

        CPU=${CPU%%.*}  # truncate for convert float to int
        echo $NAME $CPU $MAX_CPU
        if [ $CPU -gt $MAX_CPU ]; then
            echo "reach max cpu: "$NAME
            kill -9 $PID
        fi
    done
    sleep 2
done
Categories: ShellTool

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x