VBcoders Browse New Submit Contact Sign In

No account? Register free

Forgot password?

SetProcessAffinityMask API

Justin Ploski  (1 Submission)   Windows API Call/Explanation   Intermediate   Wed 3rd February 2021

This code allows you to set the process affinity on a running thread for multi processor computers.
Get the process ID of a running thread by filename. Get the process handle by the PID. Set your custom Affinity Mask. Apply the affinity mask to the process thread.

Inputs
Process Name is the only variable input. You'll need to customize the affinity mask - see comments by the MyMask assignment for information.

Assumes
This code is Windows API that allows you to specify a running process name and obtain the PID (Process ID). From the PID, it then obtains a handle on the process. You then set a custom affinity BitMask for the process, and pass the handle and affinity mask to the SetProcessAffinity function. Use GetCurrentProcess() API (always returns long -1) in place of the application handle to set the affinity on the current application. See the comments when setting the MyMask variable to customize which processors will be used. This is my first submission. I've been leeching off PlanetSourceCode for years, so I figured it's time to give something back. I've seen alot of questions but not many answers related to process affinity for multiprocessors. Please comment if you find this code useful.

Returns
The SetProcessAffinity API returns 0 if the affinity was set correctly. Anything <> 0 is an error.

Side Effects
If using a single processor machine, the only valid process affinity is CPU0.

API Declarations
Option Explicit
Private Declare Function WTSEnumerateProcesses Lib "wtsapi32.dll" Alias "WTSEnumerateProcessesA" (ByVal hServer As Long, ByVal Reserved As Long, ByVal Version As Long, ByRef ppProcessInfo As Long, ByRef pCount As Long) As Long
Private Declare Function SetProcessAffinityMask Lib "kernel32.dll" (ByVal hProcess As Long, ByVal dwProcessAffinityMask As Long) As Long
Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
Private Declare Sub WTSFreeMemory Lib "wtsapi32.dll" (ByVal pMemory As Long)
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Const WTS_CURRENT_SERVER_HANDLE = 0&
Private Type WTS_PROCESS_INFO
SessionID As Long
ProcessID As Long
pProcessName As Long
pUserSid As Long
End Type

Rate SetProcessAffinityMask API (4(4 Vote))
SetProcessAffinityMask API.bas

SetProcessAffinityMask API Comments

No comments yet — be the first to post one!

Post a Comment

0/1000 characters