Skip to content

Commit

Permalink
sysconf(NPROCESSORS_CONF) is broken on musl and they've been arguing …
Browse files Browse the repository at this point in the history
…about

it for years (https://www.openwall.com/lists/musl/2022/07/27/5) so just
inline the readdir glibc and bionic are both doing under the covers.

In theory we could also readdir for the online case, but the syscall works
when sysfs isn't mounted. (And while I'm there: never return 0.)
  • Loading branch information
landley committed Jul 28, 2022
1 parent ad5a542 commit e2b17f5
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions toys/other/taskset.c
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,26 @@ void taskset_main(void)
void nproc_main(void)
{
unsigned i, j, nproc = 0;
DIR *dd;

// This can only detect 32768 processors. Call getaffinity and count bits.
if (!toys.optflags && -1!=sched_getaffinity(getpid(), 4096, toybuf)) {
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)) nproc++;
}

// If getaffinity failed or --all, count cpu entries in proc
if (!nproc) nproc = sysconf(_SC_NPROCESSORS_CONF);
// If getaffinity failed or --all, count cpu entries in sysfs
// (/proc/cpuinfo filters out hot-unplugged CPUs, sysfs doesn't)
if (!nproc && (dd = opendir("/sys/devices/system/cpu"))) {
struct dirent *de;
char *ss;

while ((de = readdir(dd))) {
if (memcmp(de->d_name, "cpu", 3)) continue;
for (ss = de->d_name+3; isdigit(*ss); ss++);
if (!*ss) nproc++;
}
closedir(dd);
}

xprintf("%u\n", nproc);
xprintf("%u\n", nproc ? : 1);
}

0 comments on commit e2b17f5

Please sign in to comment.