diff options
-rw-r--r-- | lib/lib.h | 1 | ||||
-rw-r--r-- | lib/xwrap.c | 18 | ||||
-rw-r--r-- | toys/other/taskset.c | 23 |
3 files changed, 23 insertions, 19 deletions
@@ -136,6 +136,7 @@ void xpidfile(char *name); void xregcomp(regex_t *preg, char *rexec, int cflags); char *xtzset(char *new); void xsignal(int signal, void *handler); +unsigned xcount_cpus(void); // lib.c void verror_msg(char *msg, int err, va_list va); diff --git a/lib/xwrap.c b/lib/xwrap.c index 4880bbe0..69f891b9 100644 --- a/lib/xwrap.c +++ b/lib/xwrap.c @@ -723,3 +723,21 @@ void xsignal(int signal, void *handler) if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal); } + +unsigned xcount_cpus(void) +{ + int len = 0, i, fd = xopen("/proc/stat", O_RDONLY); + unsigned cpus = 0; + + for (;;) { + if (1>(i = xread(fd, libbuf, sizeof(libbuf)-len))) break; + len += i; + // Each cpu# line has data after it, so last 5 bytes of file can't match + for (i = 0; i<len-5; i++) + if (!strncmp(libbuf+i, "\ncpu", 4) && isdigit(libbuf[i+4])) cpus++; + memmove(libbuf, libbuf+i, 5); + } + close(fd); + + return cpus; +} diff --git a/toys/other/taskset.c b/toys/other/taskset.c index 4ade5f10..29ce3173 100644 --- a/toys/other/taskset.c +++ b/toys/other/taskset.c @@ -40,10 +40,6 @@ config TASKSET #define sched_getaffinity(pid, size, cpuset) \ syscall(__NR_sched_getaffinity, (pid_t)pid, (size_t)size, (void *)cpuset) -GLOBALS( - int nproc; -) - // mask is an array of long, which makes the layout a bit weird on big // endian systems but as long as it's consistent... @@ -120,29 +116,18 @@ void taskset_main(void) } } -static int do_nproc(struct dirtree *new) -{ - if (!new->parent) return DIRTREE_RECURSE; - if (!strncmp(new->name, "cpu", 3) && isdigit(new->name[3])) TT.nproc++; - - return 0; -} - void nproc_main(void) { - int i, j; + unsigned i, j, nproc = 0; // This can only detect 32768 processors. Call getaffinity and count bits. if (!toys.optflags && -1!=sched_getaffinity(getpid(), 4096, toybuf)) { for (i = 0; i<4096; i++) - if (toybuf[i]) - for (j=0; j<8; j++) - if (toybuf[i]&(1<<j)) - TT.nproc++; + if (toybuf[i]) for (j=0; j<8; j++) if (toybuf[i]&(1<<j)) nproc++; } // If getaffinity failed or --all, count cpu entries in proc - if (!TT.nproc) dirtree_read("/sys/devices/system/cpu", do_nproc); + if (!nproc) nproc = xcount_cpus(); - xprintf("%d\n", TT.nproc); + xprintf("%u\n", nproc); } |