taskset.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * taskset - retrieve or set a processes' CPU affinity
  4. * Copyright (c) 2006 Bernhard Fischer
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  7. */
  8. #include "busybox.h"
  9. #include <sched.h>
  10. #include <getopt.h> /* optind */
  11. #if ENABLE_FEATURE_TASKSET_FANCY
  12. #define TASKSET_PRINTF_MASK "%s"
  13. #define from_cpuset(x) __from_cpuset(&x)
  14. /* craft a string from the mask */
  15. static char *__from_cpuset(cpu_set_t *mask)
  16. {
  17. int i;
  18. char *ret = 0, *str = xzalloc(9);
  19. for (i = CPU_SETSIZE - 4; i >= 0; i -= 4) {
  20. char val = 0;
  21. int off;
  22. for (off = 0; off <= 3; ++off)
  23. if (CPU_ISSET(i+off, mask))
  24. val |= 1<<off;
  25. if (!ret && val)
  26. ret = str;
  27. *str++ = (val-'0'<=9) ? (val+48) : (val+87);
  28. }
  29. return ret;
  30. }
  31. #else
  32. #define TASKSET_PRINTF_MASK "%x"
  33. /* (void*) cast is for battling gcc: */
  34. /* "dereferencing type-punned pointer will break strict-aliasing rules" */
  35. #define from_cpuset(mask) (*(unsigned*)(void*)&(mask))
  36. #endif
  37. #define OPT_p 1
  38. int taskset_main(int argc, char** argv)
  39. {
  40. cpu_set_t mask, new_mask;
  41. pid_t pid = 0;
  42. unsigned opt;
  43. const char *state = "current\0new";
  44. char *p_opt = NULL, *aff = NULL;
  45. opt = getopt32(argc, argv, "+p:", &p_opt);
  46. if (opt & OPT_p) {
  47. if (argc == optind+1) { /* -p <aff> <pid> */
  48. aff = p_opt;
  49. p_opt = argv[optind];
  50. }
  51. argv += optind; /* me -p <arg> */
  52. pid = xatoul_range(p_opt, 1, ULONG_MAX); /* -p <pid> */
  53. } else
  54. aff = *++argv; /* <aff> <cmd...> */
  55. if (aff) {
  56. unsigned i = 0;
  57. unsigned long l = xstrtol_range(aff, 16, 1, ULONG_MAX);
  58. CPU_ZERO(&new_mask);
  59. while (i < CPU_SETSIZE && l >= (1<<i)) {
  60. if ((1<<i) & l)
  61. CPU_SET(i, &new_mask);
  62. ++i;
  63. }
  64. }
  65. if (opt & OPT_p) {
  66. print_aff:
  67. if (sched_getaffinity(pid, sizeof(mask), &mask) < 0)
  68. bb_perror_msg_and_die("failed to %cet pid %d's affinity", 'g', pid);
  69. printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
  70. pid, state, from_cpuset(mask));
  71. if (!*argv) /* no new affinity given or we did print already, done. */
  72. return EXIT_SUCCESS;
  73. }
  74. if (sched_setaffinity(pid, sizeof(new_mask), &new_mask))
  75. bb_perror_msg_and_die("failed to %cet pid %d's affinity", 's', pid);
  76. if (opt & OPT_p) {
  77. state += 8;
  78. ++argv;
  79. goto print_aff;
  80. }
  81. ++argv;
  82. execvp(*argv, argv);
  83. bb_perror_msg_and_die("%s", *argv);
  84. }
  85. #undef OPT_p
  86. #undef TASKSET_PRINTF_MASK
  87. #undef from_cpuset