pko.ch

Reflections about reflection

Taming KbdMgr.exe

I have a bootcamp’ed Macbook Pro. As many people, I experienced some lagging sound and graphics from the computer, apparently at random. I googled it a bit, and found DPCs were the cause of it. And the cause DPCs were so slow were some drivers and KbdMgr.exe, a small app that listens to the hardware keys to raise brightness and stuff.

I updated the drivers, and the lag dropped a bit, but not that much. Then I turned to KbdMgr.exe. I read that a quick fix was to set the affinity to the second core and set it to minimum priority. And so I did, and it worked! However, It was just a pain in the butt to do that dance on each boot. I thought of doing some wrapper exe for KbdMgr.exe, but just the thought of downloading Visual Studio and all the SDKs gave me nauseas. And python popped into my mind.

After some 15 minutes of research, I found win32all. And from there, It was just remembering all of the win32 I had forgotten. I eventually churned out some code to scratch my itch.

import win32api
import win32com.client
import win32process
import win32con
import time
import sys, traceback

class ProcessSeekerThrottler(object):

    def __init__(self):
        self.coup_de_grace = self.throttle_and_set_affinity
        self.backoff_interval = 1.0

    def throttle_and_set_affinity(self,pid):
        proc = win32api.OpenProcess(win32con.PROCESS_SET_INFORMATION, 0, pid)

        win32process.SetProcessAffinityMask(proc,0x02)
        win32process.SetPriorityClass(proc,win32process.IDLE_PRIORITY_CLASS)

        win32api.CloseHandle(proc)

    def pids_for(self,process_name):
        self.WMI = win32com.client.GetObject('winmgmts:')
        results = self.WMI.ExecQuery('select * from Win32_Process where Name="%s"'%(process_name,))
        if len(results) < 1:
            raise Exception("Not found: %s"%(process_name,))
        else:
            return [result.Properties_('ProcessId').Value for result in results]

    def hunt_pid_for(self,process_name):
        done = False
        while not done:
            try:
                [self.coup_de_grace(pid) for pid in self.pids_for(process_name)]
                print "Killed!"
                done = True
            except Exception as e:
                print >> sys.stderr, "-"*60
                traceback.print_exc(None,sys.stderr)
                print >> sys.stderr, "Backing off."
                time.sleep(self.backoff_interval)

if __name__ == '__main__':
    try:
        ProcessSeekerThrottler().hunt_pid_for("KbdMgr.exe")
    except Exception as e:
        traceback.print_exc(None,sys.stderr)
        raw_input()

Leave a Reply