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))
44 int taskset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
45 int taskset_main(int argc, char **argv)
47 cpu_set_t mask, new_mask;
50 const char *state = "current\0new";
51 char *p_opt = NULL, *aff = NULL;
53 opt = getopt32(argv, "+p:", &p_opt);
56 if (argc == optind+1) { /* -p <aff> <pid> */
60 argv += optind; /* me -p <arg> */
61 pid = xatoul_range(p_opt, 1, ULONG_MAX); /* -p <pid> */
63 aff = *++argv; /* <aff> <cmd...> */
66 unsigned long l = xstrtol_range(aff, 0, 1, LONG_MAX);
69 while (i < CPU_SETSIZE && l >= (1<<i)) {
71 CPU_SET(i, &new_mask);
78 if (sched_getaffinity(pid, sizeof(mask), &mask) < 0)
79 bb_perror_msg_and_die("failed to %cet pid %d's affinity", 'g', pid);
80 printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
81 pid, state, from_cpuset(mask));
82 if (!*argv) /* no new affinity given or we did print already, done. */
86 if (sched_setaffinity(pid, sizeof(new_mask), &new_mask))
87 bb_perror_msg_and_die("failed to %cet pid %d's affinity", 's', pid);
94 BB_EXECVP(*argv, argv);
95 bb_simple_perror_msg_and_die(*argv);
98 #undef TASKSET_PRINTF_MASK