Download | Plain Text | No Line Numbers


  1. /*
  2.  * simple taskset -> cpuset converter
  3.  */
  4.  
  5. #include <sys/types.h>
  6. #include <sys/sysctl.h>
  7. #include <stdio.h>
  8. #include <errno.h>
  9. #include <stdlib.h>
  10. #include <math.h>
  11. #include <stdlib.h>
  12. #include <limits.h>
  13. #include <unistd.h>
  14. #include <string.h>
  15.  
  16. void usage()
  17. {
  18. printf("Usage: taskset mask cmd [args...]\n");
  19. exit(EXIT_FAILURE);
  20. }
  21.  
  22. int main(int argc, char *argv[])
  23. {
  24. int query[2];
  25. int numcpu = 0;
  26. size_t length = sizeof(numcpu);
  27. int i;
  28. long mask;
  29. char *endptr;
  30. /* fixed buffers -> buffer overflow */
  31. char csarg[255] = "-l";
  32. char buf[10];
  33.  
  34. if (argc < 3)
  35. usage();
  36.  
  37. query[0] = CTL_HW;
  38. query[1] = HW_NCPU;
  39. if (sysctl(query, 2, &numcpu, &length, NULL, 0) == -1)
  40. {
  41. printf("Unable to query cpus: %s\n", strerror(errno));
  42. return EXIT_FAILURE;
  43. }
  44.  
  45. mask = strtol(argv[1], &endptr, 16);
  46. if ((errno == ERANGE && (mask == LONG_MAX || mask == LONG_MIN))
  47. || (errno != 0 && mask == 0))
  48. {
  49. printf("Invalid mask value\n");
  50. exit(EXIT_FAILURE);
  51. }
  52.  
  53. if (*endptr != '\0' || mask < 0)
  54. {
  55. printf("Invalid mask value. Only positive numbers allowed.\n");
  56. exit(EXIT_FAILURE);
  57. }
  58.  
  59. if (mask == 0)
  60. {
  61. printf("Mask value 0 not allowed.\n");
  62. exit(EXIT_FAILURE);
  63. }
  64.  
  65. for(i = 0; i < numcpu; ++i)
  66. {
  67. long cpuval = pow(2, i);
  68. if (mask & cpuval)
  69. {
  70. sprintf(buf, "%d,", i);
  71. strcat(csarg, buf);
  72. }
  73. }
  74.  
  75. argv[0] = "cpuset";
  76. argv[1] = csarg;
  77. return execvp(argv[0], argv);
  78. }
  79.  
  80.