进程和cpu绑定

  1. #include<stdlib.h>  
  2. #include<stdio.h>  
  3. #include<sys/types.h>  
  4. #include<sys/sysinfo.h>  
  5. #include<unistd.h>  
  6.   
  7. #define __USE_GNU  
  8. #include<sched.h>  
  9. #include<ctype.h>  
  10. #include<string.h>  
  11.   
  12. int main(int argc, char* argv[])  
  13. {  
  14.         int num = sysconf(_SC_NPROCESSORS_CONF);  
  15.         int created_thread = 0;  
  16.         int myid;  
  17.         int i;  
  18.         int j = 0;  
  19.   
  20.         cpu_set_t mask;  
  21.         cpu_set_t get;  
  22.   
  23.         if (argc != 2)  
  24.         {  
  25.                 printf("usage : ./cpu num/n");  
  26.                 exit(1);  
  27.         }  
  28.   
  29.         myid = atoi(argv[1]);  
  30.   
  31.         printf("system has %i processor(s). /n", num);  
  32.   
  33.         CPU_ZERO(&mask);  
  34.         CPU_SET(myid, &mask);  
  35.   
  36.         if (sched_setaffinity(0, sizeof(mask), &mask) == -1)  
  37.         {  
  38.                 printf("warning: could not set CPU affinity, continuing.../n");  
  39.         }  
  40.         while (1)  
  41.         {  
  42.   
  43.                 CPU_ZERO(&get);  
  44.                 if (sched_getaffinity(0, sizeof(get), &get) == -1)  
  45.                 {  
  46.                         printf("warning: cound not get cpu affinity, continuing.../n");  
  47.                 }  
  48.                 for (i = 0; i < num; i++)  
  49.                 {  
  50.                         if (CPU_ISSET(i, &get))  
  51.                         {  
  52.                                 printf("this process %d is running processor : %d/n",getpid(), i);  
  53.                         }  
  54.                 }  
  55.         }  
  56.         return 0;  
  57. }  
posted @ 2016-01-18 16:19  OracleLoyal  阅读(438)  评论(0编辑  收藏  举报