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