setting process affinity in windows in command line @ 1/17/2012

programming & research
If you need to bind a process to some specific cores, you can use the "Set Affinity" function in taskmgr.exe. Open task manager->processes->right click a process->set affinity.

However, if you want to set affinity in command line, you will need some tools. Here is a program I wrote to deal with this:


#include <iostream>
#include <sstream>
using namespace std;

#include <Windows.h>


int main(int argc, char ** argv)
{
    if(argc!=3)
    {
        cout<<"usage: "<< argv[0] << " pid mask" <<endl;
        return 1;
    }

    int pid = 0;
    istringstream sspid(argv[1]);
    sspid>>pid;
    if(pid<=0)
    {
        cout<<"bad pid"<<endl;
        return 1;
    }

    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
    if(!hProcess)
    {
        cout<<"cannot open the process"<<endl;
        return 1;
    }

    string mask_str = argv[2];
    DWORD_PTR mask = 0;
    if(mask_str.size()>sizeof(mask)*8)
    {
        cout<<"mask is too long: mask_size="<<mask_str.size()<<", sizeof(mask)="<<sizeof(mask)*8<<endl;
        return 1;
    }

    for(int i=mask_str.size()-1; i>=0;i--)
    {
        mask = mask<<1;
        if(mask_str[i]=='1')
        {
            mask |= 1;
        }
    }

    if( !SetProcessAffinityMask(hProcess, mask) )
    {
        cout<<"error setting affinity mask: "<<mask<<endl;
        cout<<"error num: "<<GetLastError()<<endl;
        CloseHandle(hProcess);
        return 1;
    }
    CloseHandle(hProcess);
    return 0;
}


Compile the code with Visual C++, and use it like this:
  C:>\ setaffinity.exe [pid] [mask]

The mask is a binary number string. e.g. "1011" will bind the process to cores #0, #2 and #3.
For more information, check out my github project: https://github.com/hjk41/setaffinity_windows
发布于 1/17/2012 11:47:53 | 评论:0

看帖要回帖...