Is it possible to set the processor affinity of a service, and persist this affinity across reboots?

8,747

Some services, such as IIS, are built with the ability to read a bitmask from the registry and use that to set their own CPU affinity when they start, but that is not a feature of every service.

I would probably create a task that is set to fire on an event, and the event would be "MyService service is started" ... in the System event log. The task would then run this Powershell code:

# TODO: Add error checking
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public class Affinity
{
    [DllImport("kernel32.dll")]
    static extern bool SetProcessAffinityMask(IntPtr Handle, UIntPtr AffinityMask);

    public static void SetAffinity(IntPtr Handle, UIntPtr AffinityMask)
    {
        SetProcessAffinityMask(Handle, AffinityMask);
    }
}    
'@

$Process = Get-Process MyService
If (-Not($Process))
{
    Return
}

# This is a bitmask.
$AffinityMask = New-Object UIntPtr 1

# TODO: Foreach loop to set affinity for each instance of the process
[Affinity]::SetAffinity($Process.Handle, $AffinityMask)

EDIT: Hahah, I'm sorry, that's way more complicated than it needs to be. Powershell already has this ability built in to it by simply doing:

$Process = Get-Process MyService
$Process.ProcessorAffinity = 1

A bitmask means that a decimal value 1 means "the first CPU only," a decimal value of 2 (binary 10) means "the second CPU only," a decimal value of 3 (binary 11) means "CPUs 1 and 2," and so on and so forth.

Share:
8,747

Related videos on Youtube

EGr
Author by

EGr

Updated on September 18, 2022

Comments

  • EGr
    EGr almost 2 years

    Is there a setting that can be changed (or a reg key that can be added) to set the processor affinity of a service? I would want to set the affinity, and keep this setting across reboots (so manually changing the affinity after starting the service will not work for me).