Skip to content

Instantly share code, notes, and snippets.

@andrwj
Last active January 1, 2016 13:39
Show Gist options
  • Save andrwj/8152398 to your computer and use it in GitHub Desktop.
Save andrwj/8152398 to your computer and use it in GitHub Desktop.
Set CPU limits on pattern matched processes
#!/bin/bash
# A.J <[email protected]>
# 2013-12-27
# v0.0.2
#
# set cpu limit on pattern matched processes
# default limit value: 10%
# usage:
# climit.to <['process-name' | 'kill-all']> [value-to-limit-in-percentage]"
#
default_target=__none__
temporary_list_file="/tmp/$$.list"
previous_cpulimit_pid_file="/tmp/$$.dup"
target=${1:-$default_target}
limit=${2:-10}
cmd=/usr/local/bin/cpulimit
# don't left garbage ..
function clean_up {
rm -f $temporary_list_file
rm -f $previous_cpulimit_pid_file
echo
}
trap clean_up SIGHUP SIGINT SIGTERM
if [[ "$target" == "__none__" ]]; then
echo "CPU limit for all matched processes v0.0.1 by A.J<[email protected]>"
echo "Usage: climit.to <['process-name'|'kill-all']> [value-to-limit-in-percentage]"
echo " i.e: climit.to 'Google Chrome Helper' 10"
echo ""
echo "-- running cpulimits -- "
ps -ax | grep cpulimit | grep '\-\-pid='
clean_up
fi
if [[ "$target" == "kill-all" ]]; then
echo -n "stopping all cpu-limits ..."
killall cpulimit
clean_up
fi
if [[ ! -e "$cmd" ]]; then
echo "- compile and install: cpulimit ..."
brew install cpulimit
if [[ $? -ne 0 ]]; then
echo
echo "- cpulimit is not presented. abort ";
echo
clean_up
fi
echo
fi
ps -ax | grep "$target" > $temporary_list_file
while IFS=' ' read -r process_id tty _time path args; do
# damn ;-)
if [[ "$path" == "grep" || "$path" == "/bin/bash" ]]; then
continue;
fi
rm -f $previous_cpulimit_pid_file
ps -ax | grep 'cpulimit' | grep "pid=$process_id" > $previous_cpulimit_pid_file
while IFS=' ' read -r previous_cpulimit_pid dummy dummy; do
if [[ ! -z $previous_cpulimit_pid ]]; then
echo
echo -n "- Cancel previous cpulimit process($previous_cpulimit_pid) ..."
kill -TERM $previous_cpulimit_pid > /dev/null
if [ $? -eq 0 ]; then
echo " ok"
else
echo " failed. you should check out."
fi
fi
done <"$previous_cpulimit_pid_file"
$cmd --limit=$limit --pid=$process_id -z 2>&1 > /dev/null &
echo "=> Set cpu usage limitation '${limit}%' to the process($path)"
done <"$temporary_list_file"
clean_up
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment