1 /* vi: set sw=4 ts=4: */
3 * taskset - retrieve or set a processes' CPU affinity
4 * Copyright (c) 2006 Bernhard Fischer
6 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10 #include <getopt.h> /* optind */
13 #if ENABLE_FEATURE_TASKSET_FANCY
14 #define TASKSET_PRINTF_MASK "%s"
15 #define from_cpuset(x) __from_cpuset(&x)
16 /* craft a string from the mask */
17 static char *__from_cpuset(cpu_set_t *mask)
20 char *ret = 0, *str = xzalloc(9);
22 for (i = CPU_SETSIZE - 4; i >= 0; i -= 4) {
25 for (off = 0; off <= 3; ++off)
26 if (CPU_ISSET(i+off, mask))
31 *str++ = (val-'0'<=9) ? (val+48) : (val+87);
36 #define TASKSET_PRINTF_MASK "%x"
37 /* (void*) cast is for battling gcc: */
38 /* "dereferencing type-punned pointer will break strict-aliasing rules" */
39 #define from_cpuset(mask) (*(unsigned*)(void*)&(mask))
43 int taskset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
44 int taskset_main(int argc ATTRIBUTE_UNUSED, char **argv)
49 const char *current_new;
51 char *aff = aff; /* for compiler */
53 /* NB: we mimic util-linux's taskset: -p does not take
54 * an argument, i.e., "-pN" is NOT valid, only "-p N"!
55 * Indeed, util-linux-2.13-pre7 uses:
56 * getopt_long(argc, argv, "+pchV", ...), not "...p:..." */
58 opt_complementary = "-1"; /* at least 1 arg */
59 opt_p = getopt32(argv, "+p");
64 if (*argv) { /* "-p <aff> <pid> ...rest.is.ignored..." */
66 pid_str = *argv; /* NB: *argv != NULL in this case */
68 /* else it was just "-p <pid>", and *argv == NULL */
69 pid = xatoul_range(pid_str, 1, ((unsigned)(pid_t)ULONG_MAX) >> 1);
71 aff = *argv++; /* <aff> <cmd...> */
76 current_new = "current\0new";
79 if (sched_getaffinity(pid, sizeof(mask), &mask) < 0)
80 bb_perror_msg_and_die("can't %cet pid %d's affinity", 'g', pid);
81 printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
82 pid, current_new, from_cpuset(mask));
84 /* Either it was just "-p <pid>",
85 * or it was "-p <aff> <pid>" and we came here
86 * for the second time (see goto below) */
90 current_new += 8; /* "new" */
93 { /* Affinity was specified, translate it into cpu_set_t */
95 /* Do not allow zero mask: */
96 unsigned long long m = xstrtoull_range(aff, 0, 1, ULLONG_MAX);
97 enum { CNT_BIT = CPU_SETSIZE < sizeof(m)*8 ? CPU_SETSIZE : sizeof(m)*8 };
100 for (i = 0; i < CNT_BIT; i++) {
101 unsigned long long bit = (1ULL << i);
107 /* Set pid's or our own (pid==0) affinity */
108 if (sched_setaffinity(pid, sizeof(mask), &mask))
109 bb_perror_msg_and_die("can't %cet pid %d's affinity", 's', pid);
111 if (!*argv) /* "-p <aff> <pid> [...ignored...]" */
112 goto print_aff; /* print new affinity and exit */
114 BB_EXECVP(*argv, argv);
115 bb_simple_perror_msg_and_die(*argv);