简体   繁体   中英

How to get process to set it's affinity?

I'm trying to get the process to set it's affinity using the below program. But i want to set the affinity of chrome or any other process. How to do that?

#include <windows.h>
#include <iostream>

using namespace std;
void main(){


    HANDLE process = GetCurrentProcess();
    DWORD_PTR processAffinityMask = 8;

    BOOL success = SetProcessAffinityMask(process, processAffinityMask);
    SetPriorityClass(GetCurrentProcess(), THREAD_PRIORITY_TIME_CRITICAL);

    cout << success << endl;

    system("pause");
}

To obtain the process ID of an arbitrarily-named process you can do:

#include <Windows.h>
#include <string>
#include <tlhelp32.h>

int getPID(const std::string& process_name)
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (!Process32First(snapshot, &entry)) return 0;

    do
    {
        if (strcmp(entry.szExeFile, process_name.c_str()) == 0)
        {
            CloseHandle(snapshot);
            return entry.th32ProcessID;
        }
    } while (Process32Next(snapshot, &entry));

    CloseHandle(snapshot);
    return 0;
}

You can then obtain a handle to that process as follows:

HANDLE hProcess = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);

And finally you can pass hProcess to SetProcessAffinityMask and SetPriorityClass in the usual way.

I believe you need to be running elevated (ie as Administrator) for this to work - and do test that OpenProcess succeeded and report the result of calling GetLastError if not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM