3
0

taskset.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 <unistd.h>
  11. #include <getopt.h> /* optind */
  12. #if ENABLE_FEATURE_TASKSET_FANCY
  13. #define TASKSET_PRINTF_MASK "%s"
  14. #define from_cpuset(x) __from_cpuset(&x)
  15. /* craft a string from the mask */
  16. static char *__from_cpuset(cpu_set_t *mask) {
  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. #define from_cpuset(mask) mask
  34. #endif
  35. #define TASKSET_OPT_p (1)
  36. int taskset_main(int argc, char** argv)
  37. {
  38. cpu_set_t mask, new_mask;
  39. pid_t pid = 0;
  40. unsigned long ul;
  41. const char *state = "current\0new";
  42. char *p_opt = NULL, *aff = NULL;
  43. ul = getopt32(argc, argv, "+p:", &p_opt);
  44. if (ul & TASKSET_OPT_p) {
  45. if (argc == optind+1) { /* -p <aff> <pid> */
  46. aff = p_opt;
  47. p_opt = argv[optind];
  48. }
  49. argv += optind; /* me -p <arg> */
  50. pid = xatoul_range(p_opt, 1, ULONG_MAX); /* -p <pid> */
  51. } else
  52. aff = *++argv; /* <aff> <cmd...> */
  53. if (aff) {
  54. unsigned i = 0;
  55. unsigned long l = xstrtol_range(aff, 16, 1, ULONG_MAX);
  56. CPU_ZERO(&new_mask);
  57. while (i < CPU_SETSIZE && l >= (1<<i)) {
  58. if ((1<<i) & l)
  59. CPU_SET(i, &new_mask);
  60. ++i;
  61. }
  62. }
  63. if (ul & TASKSET_OPT_p) {
  64. print_aff:
  65. if (sched_getaffinity(pid, sizeof (mask), &mask) < 0)
  66. bb_perror_msg_and_die("Failed to %cet pid %d's affinity", 'g', pid);
  67. printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
  68. pid, state, from_cpuset(mask));
  69. if (!*argv) /* no new affinity given or we did print already, done. */
  70. return EXIT_SUCCESS;
  71. }
  72. if (sched_setaffinity(pid, sizeof (new_mask), &new_mask))
  73. bb_perror_msg_and_die("Failed to %cet pid %d's affinity", 's', pid);
  74. if (ul & TASKSET_OPT_p) {
  75. state += 8;
  76. ++argv;
  77. goto print_aff;
  78. }
  79. ++argv;
  80. execvp(*argv, argv);
  81. bb_perror_msg_and_die("%s", *argv);
  82. }
  83. #undef TASKSET_OPT_p
  84. #undef TASKSET_PRINTF_MASK
  85. #undef from_cpuset