Thursday, September 29, 2005

Hello Process!

I just created my first Windows service. Its sole purpose in life is to look for a Firefox process once a second and, if one is found, sets its CPU affinity to CPU0.

Works like a charm. :)

In lieu of posting binaries, which is what I'd much rather be doing, here's the source code, written in C# in Visual Studio 2005 RC. The trick is adding the service installer and using installutil.exe to install the service assembly. See Adding Installers to Your Service Application on MSDN.

I love .NET. I was intimidated by all the stuff I saw in MSDN about setting affinity until I got to .NET. Mmmm. Process.ProcessorAffinity()... Auughghghghghghh...

namespace AffinityMonitor
{
    public partial class AffinityMonitor : ServiceBase
    {
        public AffinityMonitor()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.Diagnostics.EventLog.WriteEntry("AffinityMonitor", "AffinityMonitor service started");
            backgroundWorker1.RunWorkerAsync();
        }

        protected override void OnStop()
        {
            System.Diagnostics.EventLog.WriteEntry("AffinityMonitor", "AffinityMonitor service stopping");
            backgroundWorker1.CancelAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Console.WriteLine("Tick!");
                Process[] processes = Process.GetProcessesByName("firefox");
                foreach (Process p in processes)
                {
                    p.ProcessorAffinity = new IntPtr(1);
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

2 Comments:

Blogger BlackTigerX said...

so if you are running FireFox, it just keeps doing that over and over and over every second... mmm...

9/30/2005 10:45:00 AM  
Blogger Jeff Stewart said...

Yep. Works like a charm. :)

Mind you, I devoted the sum total of 10 minutes to this project because I finally got fed up with using Task Manager to set the CPU affinity. I was unable to find anything but command-line bootstrappers to solve the problem, and generally favor services that centralize the effort, especially in light of having to modify dozens of shortcuts.

If enough programs o' mine display this irritating behavior, then I'll build a much more robust system that keeps track of which process IDs have been touched. I'd like to find a way for the service to be alerted when new processes are created, rather than relying on an arbitrary polling mechanism.

It's a prototype, and right now it works without any performance impact, so I like it. :)

9/30/2005 10:59:00 AM  

Post a Comment

<< Home