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 #include <getopt.h> /* optind */
14 #if ENABLE_FEATURE_TASKSET_FANCY
15 #define TASKSET_PRINTF_MASK "%s"
16 #define from_cpuset(x) __from_cpuset(&x)
17 /* craft a string from the mask */
18 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 #define from_cpuset(mask) mask
40 #define TASKSET_OPT_p (1)
42 int taskset_main(int argc, char** argv)
44 cpu_set_t mask, new_mask;
47 const char *state = "current\0new";
48 char *p_opt = NULL, *aff = NULL;
50 ul = getopt32(argc, argv, "+p:", &p_opt);
52 if (ul & TASKSET_OPT_p) {
53 if (argc == optind+1) { /* -p <aff> <pid> */
57 argv += optind; /* me -p <arg> */
58 pid = xatoul_range(p_opt, 1, ULONG_MAX); /* -p <pid> */
60 aff = *++argv; /* <aff> <cmd...> */
63 unsigned long l = xstrtol_range(aff, 16, 1, ULONG_MAX);
66 while (i < CPU_SETSIZE && l >= (1<<i)) {
68 CPU_SET(i, &new_mask);
73 if (ul & TASKSET_OPT_p) {
75 if (sched_getaffinity(pid, sizeof (mask), &mask) < 0)
76 bb_perror_msg_and_die("Failed to %cet pid %d's affinity", 'g', pid);
77 printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
78 pid, state, from_cpuset(mask));
79 if (!*argv) /* no new affinity given or we did print already, done. */
83 if (sched_setaffinity(pid, sizeof (new_mask), &new_mask))
84 bb_perror_msg_and_die("Failed to %cet pid %d's affinity", 's', pid);
85 if (ul & TASKSET_OPT_p) {
92 bb_perror_msg_and_die("%s", *argv);
95 #undef TASKSET_PRINTF_MASK