Skip to content

Commit e2882b4

Browse files
committed
Add nproc.
1 parent 324e615 commit e2882b4

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

toys/other/taskset.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,17 @@
33
* Copyright 2012 Elie De Brauwer <eliedebrauwer@gmail.com>
44
55
USE_TASKSET(NEWTOY(taskset, "<1^pa", TOYFLAG_BIN|TOYFLAG_STAYROOT))
6+
USE_NPROC(NEWTOY(nproc, "(all)", TOYFLAG_USR|TOYFLAG_BIN))
7+
8+
config NPROC
9+
bool "nproc"
10+
default y
11+
help
12+
usage: nproc [--all]
13+
14+
Print number of processors.
15+
16+
--all Show all processors, not just ones this task can run on.
617
718
config TASKSET
819
bool "taskset"
@@ -29,6 +40,10 @@ config TASKSET
2940
#define sched_getaffinity(pid, size, cpuset) \
3041
syscall(__NR_sched_getaffinity, (pid_t)pid, (size_t)size, (void *)cpuset)
3142

43+
GLOBALS(
44+
int nproc;
45+
)
46+
3247
// mask is an array of long, which makes the layout a bit weird on big
3348
// endian systems but as long as it's consistent...
3449

@@ -104,3 +119,30 @@ void taskset_main(void)
104119
} else do_taskset(pid, 0);
105120
}
106121
}
122+
123+
int do_nproc(struct dirtree *new)
124+
{
125+
if (!new->parent) return DIRTREE_RECURSE;
126+
if (!strncmp(new->name, "cpu", 3) && isdigit(new->name[3])) TT.nproc++;
127+
128+
return 0;
129+
}
130+
131+
void nproc_main(void)
132+
{
133+
int i, j;
134+
135+
// This can only detect 32768 processors. Call getaffinity and count bits.
136+
if (!toys.optflags && -1!=sched_getaffinity(getpid(), 4096, toybuf)) {
137+
for (i = 0; i<4096; i++)
138+
if (toybuf[i])
139+
for (j=0; j<8; j++)
140+
if (toybuf[i]&(1<<j))
141+
TT.nproc++;
142+
}
143+
144+
// If getaffinity failed or --all, count cpu entries in proc
145+
if (!TT.nproc) dirtree_read("/sys/devices/system/cpu", do_nproc);
146+
147+
xprintf("%d\n", TT.nproc);
148+
}

0 commit comments

Comments
 (0)