I have created a script that kills processes if CPU and/or memory usage hits 80%. It creates a list of killed processes when this happens. What can I do to improve it?while [ 1 ];do echoecho checking for run-away process ...CPU_USAGE=$(uptime | cut -d, -f4 | cut -d: -f2 | cut -d  -f2 | sed -e s/\.//g)CPU_USAGE_THRESHOLD=800PROCESS=$(ps aux r)TOPPROCESS=$(ps -eo pid -eo pcpu -eo command | sort -k 2 -r | grep -v PID | head -n 1)if [ $CPU_USAGE -gt $CPU_USAGE_THRESHOLD] ; then  kill -9 $(ps -eo pid | sort -k 1 -r | grep -v PID | head -n 1) #original  kill -9 $(ps -eo pcpu | sort -k 1 -r | grep -v %CPU | head -n 1)  kill -9 $TOPPROCESS  echo system overloading!  echo Top-most process killed $TOPPROCESS      echo CPU USAGE is at $CPU_LOADelse    fi    exit 0    sleep 1;    done
Bash script that automatically kills processes when CPU/memory usage gets too high
bash;shell script;memory;cpu;cpu usage
I'm guessing the problem you want to solve is that you have some process running on your box which sometimes misbehaves, and sits forever pegging a core.The first thing you want to do is to attempt to fix the program that goes crazy. That is by far the best solution. I'm going to assume that isn't possible, or you need a quick kluge to keep your box running until its fixed.You, at minimum, want to limit your script to only hit the one program you're concerned about. It'd be best if permissions limited your script like this (e.g., your script runs as user X, the only other thing running as X is the program).Even better would be to use something like ulimit -t to limit the amount of total CPU time that the program can use. Similarly, if it consumes all memory, check ulimit -v. The kernel enforces these limits; see the bash manpage (it's a shell built-in) and the setrlimit(2) manpage for details.If the problem isn't a process running amok, but is instead just too many processes running, then implement some form of locking to prevent more than X from running (orthis should be getting familiarulimit -u). You may also consider changing the scheduler priority of those processes (using nice or renice), or for even more drastic, using sched_setscheduler to change the policy to SCHED_IDLE. If you need even more control, take a look a control groups (cgroups). Depending on the kernel you're running, you can actually limit the amount of CPU time, memory, I/O, etc. that a whole group of processes together consume. Control groups are quite flexible; they can likely do whatever you're trying to do, without any fragile kluges. The Arch Linux Wiki has an intro to cgroups that's worth reading, as is Neil Brown's cgroups series at LWN.