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.
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)
19 char *ret = 0, *str = xzalloc(9);
21 for (i = CPU_SETSIZE - 4; i >= 0; i -= 4) {
24 for (off = 0; off <= 3; ++off)
25 if (CPU_ISSET(i+off, mask))
30 *str++ = (val-'0'<=9) ? (val+48) : (val+87);
35 #define TASKSET_PRINTF_MASK "%x"
36 /* (void*) cast is for battling gcc: */
37 /* "dereferencing type-punned pointer will break strict-aliasing rules" */
38 #define from_cpuset(mask) (*(unsigned*)(void*)&(mask))
42 int taskset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
43 int taskset_main(int argc UNUSED_PARAM, char **argv)
48 const char *current_new;
50 char *aff = aff; /* for compiler */
52 /* NB: we mimic util-linux's taskset: -p does not take
53 * an argument, i.e., "-pN" is NOT valid, only "-p N"!
54 * Indeed, util-linux-2.13-pre7 uses:
55 * getopt_long(argc, argv, "+pchV", ...), not "...p:..." */
57 opt_complementary = "-1"; /* at least 1 arg */
58 opt_p = getopt32(argv, "+p");
63 if (*argv) { /* "-p <aff> <pid> ...rest.is.ignored..." */
65 pid_str = *argv; /* NB: *argv != NULL in this case */
67 /* else it was just "-p <pid>", and *argv == NULL */
68 pid = xatoul_range(pid_str, 1, ((unsigned)(pid_t)ULONG_MAX) >> 1);
70 aff = *argv++; /* <aff> <cmd...> */
75 current_new = "current\0new";
78 if (sched_getaffinity(pid, sizeof(mask), &mask) < 0)
79 bb_perror_msg_and_die("can't %cet pid %d's affinity", 'g', pid);
80 printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
81 pid, current_new, from_cpuset(mask));
83 /* Either it was just "-p <pid>",
84 * or it was "-p <aff> <pid>" and we came here
85 * for the second time (see goto below) */
89 current_new += 8; /* "new" */
92 { /* Affinity was specified, translate it into cpu_set_t */
94 /* Do not allow zero mask: */
95 unsigned long long m = xstrtoull_range(aff, 0, 1, ULLONG_MAX);
96 enum { CNT_BIT = CPU_SETSIZE < sizeof(m)*8 ? CPU_SETSIZE : sizeof(m)*8 };
99 for (i = 0; i < CNT_BIT; i++) {
100 unsigned long long bit = (1ULL << i);
106 /* Set pid's or our own (pid==0) affinity */
107 if (sched_setaffinity(pid, sizeof(mask), &mask))
108 bb_perror_msg_and_die("can't %cet pid %d's affinity", 's', pid);
110 if (!*argv) /* "-p <aff> <pid> [...ignored...]" */
111 goto print_aff; /* print new affinity and exit */
113 BB_EXECVP(*argv, argv);
114 bb_simple_perror_msg_and_die(*argv);