1、设置进程的cpu亲和性程序如下,

#Using:g++ setCpuAffinity.c -o setCpuAffinity

#include<sys/types.h>
#include<sys/sysinfo.h>
#include<unistd.h> //#define __USE_GNU
#include<sched.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h> int main(int argc, char* argv[])
{
int num = sysconf(_SC_NPROCESSORS_CONF);
int created_thread = ;
int myid, pid;
int i;
int j = ; cpu_set_t mask;
cpu_set_t get; if (argc < )
{
printf("usage : ./setAffinity pid num1,num2,..,numn \n");
exit();
} pid = atoi(argv[]);
CPU_ZERO(&mask);
for (i = ; i < argc; i++)
{
myid = atoi(argv[i]);
CPU_SET(myid, &mask);
}
if (sched_setaffinity(pid, sizeof(mask), &mask) == -)
{
printf("warning: could not set CPU affinity, continuing...\n");
} else {
printf("sched_setaffinity succeed !!!\n"); }
}

 2、获取进程的CPU亲和性程序如下,

#Using:g++ getCpuAffinity.c -o getCpuAffinity

#include<sys/types.h>
#include<sys/sysinfo.h>
#include<unistd.h> //#define __USE_GNU
#include<sched.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h> int main(int argc, char* argv[])
{
int num = sysconf(_SC_NPROCESSORS_CONF);
int pid;
int i; cpu_set_t get; if (argc != )
{
printf("usage : ./setAffinity pid \n");
exit();
} pid = atoi(argv[]); CPU_ZERO(&get);
if (sched_getaffinity(pid, sizeof(get), &get) == -)
{
printf("warning: cound not get cpu affinity, continuing...\n");
}
for (i = ; i < num; i++)
{
if (CPU_ISSET(i, &get))
{
printf("this process %d is running processor : %d\n", pid, i);
}
}
}
05-02 23:34