Skip to content

Instantly share code, notes, and snippets.

@dmgr
Last active September 23, 2015 10:01
Show Gist options
  • Save dmgr/08f9dc89095eab4c74b5 to your computer and use it in GitHub Desktop.
Save dmgr/08f9dc89095eab4c74b5 to your computer and use it in GitHub Desktop.
cpulimit background processes
def all_ps
# res = `ps -fxo pid,comm | awk '$2 ~ /_/ { print $1, $3 }'`
res = `ps -xo pid,comm`.downcase
res.lines.map { |line| line.split(/\s+/).last(2) }
end
def foreground_pid
command = 'ps -o pid,comm $(xprop -id $(xprop -root -f _NET_ACTIVE_WINDOW 0x " \$0\\n" _NET_ACTIVE_WINDOW | awk "{ print \$2 }") -f _NET_WM_PID 0c " \$0\\n" _NET_WM_PID | awk "{print \$2}")'
res = `#{ command }`
res.lines.last.split(/\s+/).last(2)
end
def cpulimitted
res = `pgrep cpulimit -a`
res.lines.map { |line| [line.split(/\s+/)[0], line] }
end
def main
fpid, fpname = foreground_pid
cpulimitted = cpulimitted()
puts "Foreground app: #{ fpname } #{ fpid }"
ps_map = {
'firefox' => true,
'chrome' => :multi,
'chromium-browse' => :multi,
}
all_ps.each do |pid, pname|
catch :break do
if config = ps_map[pname]
puts "Analyzing #{ pid } #{ pname }"
#ps_map[pname] = false if config == :multi
if pid == fpid || config == :multi && fpname == pname
# CPU no limit
cpulimitted.each do |cpulimitpid, command|
if command[pid]
puts "Killing cpulimit for #{ pname }: #{ command }"
`kill #{ cpulimitpid }`
end
end
else
# CPU limit
cpulimitted.each do |cpulimitpid, command|
throw :break if command[pid]
end
puts "cpulimit for #{ pname } (#{ pid })."
Thread.new do
`renice 7 #{ pid } && cpulimit -p #{ pid } -l 1 -z -b &`
end
end
end
end
end
end
loop do
main()
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment