Controlling Process CPU Utilization
Let’s say there is a process on your Unix/Linux system that sometimes tends to consume all CPU resources and become unresponsive. At the same time, you do not want to terminate the process at the first sign of trouble, because momentary high CPU utilization may be legitimate. The solution is to continuously calculate the running average of CPU utilization. Korn shell array is a good tool for storing intermediate values and calculating the average. Below is a sample script that will terminate the monitored process (process.bin) if it exceeds CPU utilization limit during the specified period of time.
#!/bin/ksh configure() { COMMAND="process.bin" # Name of the process being monitored CPULIMIT=99 # CPU threshold LOOP=10 # Monitor process every so many seconds INTERVAL_DURATION=1 # Take CPU utilization readings every so many seconds INTERVAL_COUNT="0 1 2 3 4" # Calculate average based on this many readings } pid() { PID=99999999 PID=$(ps -ef | grep $COMMAND | grep -v grep | awk '{print $2}' | sort | uniq | tail -1) } cpu() { CPU=0 CPUAVG=0 CPU=$(top -b -n 1 -p $PID | grep $COMMAND | awk '{print $9}') if [ $CPU -ge $CPULIMIT ] then for i in $INTERVAL_COUNT # If CPU load exceeds $CPULIMIT, determine average CPU load do array[$i]=$(top -b -n 1 -p $PID | grep $COMMAND | awk '{print $9}') sleep $INTERVAL_DURATION done CPUAVG=$(echo "scale = 0 ; (${array[0]}+${array[1]}+${array[2]}+${array[3]}+${array[4]})/5" | bc -l) fi } terminate() { if [ $CPUAVG -ge $CPULIMIT ] then kill -9 $PID echo "Killed $PID at `date`" fi } # ------------------------------- # RUNTIME # ------------------------------- configure # Configure script parameters i=1 while [ $i -eq 1 ] # Run script in a loop every $LOOP seconds do pid # Aquire unique PID of the $COMMAND cpu # Determine current CPU load for the $COMMAND terminate # Kill $COMMAND if $CPULIMIT is exceeded sleep $LOOP done
Popularity: 4% [?]
Related posts:


