Ubuntu – How to Limit the CPU usage for a process and its children whether there is another process demanding resources or not

12.04cpucpu loadperformance

I was thinking about using CPUlimit to limit process CPU usage, but I am aiming to apply the same percentage of usage for its child processes too automatically.

Is there something that can limits the CPU usage for a process and its children whether there is or there is not another process needing resources at the same time?

cgroup cpu.shares limits only when there is another process needing the resources consumed by a previous process. What I'm looking for is something like sudo cpulimit -p 1234 -l 20 so the limit on cpu usage doesn't consider whether there is another process or not demanding the used resources.

This was applied to the parent process (pid =1234) but not its children.

Best Answer

This link may help Set maximum CPU consumption in percentage by any process searched by : MrSeed

this script may help too , any any one wants to enter suggestions on this script to enhance it , it will be my pleasure

       #!/bin/bash -xv

read -p "Which program u want to limit its processes?" ProgrameName
read -p "Which limitation percentage u want for it ?" limitationPercentage  
read -p "Period to be sleep " sleepInterval 
dataFile="/home/ahmedubuntu/Desktop/.file.txt"
separator="######"
trap "echo \"\" > $dataFile"  SIGINT SIGTERM SIGHUP
########################################################
if [ -e $dataFile ]; then
  echo "File $dataFile already exists!"
  echo -e "" > $dataFile
else
  echo >> $dataFile
fi 
echo -e "$ProgrameName \n $limitationPercentage \n" >> $dataFile
getAllPIDRunUnderThisProgram=$( ps -e | grep "$ProgrameName" | awk '{print $1;}')
echo -e "${getAllPIDRunUnderThisProgram[@]}  \n $separator \n" >> $dataFile
for i in $getAllPIDRunUnderThisProgram
   do
    gnomeTab+=( --tab -e "cpulimit -p $i -l $limitationPercentage ")  
   done
gnome-terminal "${gnomeTab[@]}"
#echo gnome-terminal "${gnomeTab[@]}"
########################################################
while sleep $sleepInterval
do
i=0
while read line
do
if [ -n "$line" ] && ["$line" != "separator"] 
then
programeNameAndPID[i]=$line
((i++))
elif [["$line" == "separator"]] ; then
getAllPIDRunUnderThisProgram=$( ps -e | grep "$programeNameAndPID[0]" | awk '{print $1;}')
if [${#getAllPIDRunUnderThisProgram[*]} -gt ${#programeNameAndPID[*]}-2  ]
then
unset gnomeTab
newProcessNumber=${#getAllPIDRunUnderThisProgram[*]}-${#programeNameAndPID[*]}-2
index=${#getAllPIDRunUnderThisProgram[*]}-1
for (( c=$newProcessNumber ; c > 0 ; c-- ))
do
gnomeTab+=( --tab -e "cpulimit -p $getAllPIDRunUnderThisProgram[$index] -l $programeNameAndPID[1] ") 
((index--)) 
done
gnome-terminal "${gnomeTab[@]}"
fi
i=0
unset programeNameAndPID
fi
done < $dataFile
done

and by adding nice -10 will work well with no need to sudo and password