Stop Firefox (and other X-Window clients) from wasting my CPU

Submitted by olaf on 2016-12-05

Because the Compiz window manager messed up my desktop several times, I switched to awesome wm recently. Awesome uses Lua as its configuration language. It also allows to hook into several events by connecting to so called signals.

Two of these signals are focus and unfocus. With these signals, I can run some Lua function, when I switch to or from a client. One application of these signals is halting and restarting processes, when they get or lose the focus.

Typically I have two clients, which benefit from this treatment, Firefox and the Android (QEmu) emulator. (Compiz was already taken care of by awesome wm :-). Both are constantly running and using CPU resources, even when I switch away and they should be idle.

To do this, I added a callback to awful.rules, which connects to the focus and unfocus signals for specific clients.

local function resource_hog_client_rule(c)
   c:connect_signal("focus", enable_client)
   c:connect_signal("unfocus", disable_client)
end

awful.rules.rules = {
    -- other rules
    -- ...
    { rule_any = { class = { "Firefox", "emulator64-arm" } },
      callback = resource_hog_client_rule
    },
}

Both enable_client and disable_client are pretty simple, they just call kill -cont or kill -stop respectively.

local function enable_client(c)
   local cmd = 'kill -cont ' .. c.pid
   os.execute(cmd)
end

local function disable_client(c)
   local cmd = 'kill -stop ' .. c.pid
   os.execute(cmd)
end

This way a client is put to sleep, when I switch to another application, and woken up again when it receives the focus.

Note although, that this doesn’t work, when a client runs as another user, or when a client runs in a container. In the first case, you don’t have permission to send a system signal to the client process. In the second case, the process id (c.pid) from inside the container will be different from the process id where awesome runs.

Post a comment

All comments are held for moderation; Markdown and basic HTML formatting accepted. If you want to stay anonymous, leave name, e-mail and website empty.