3
3
* Copyright 2012 Elie De Brauwer <eliedebrauwer@gmail.com>
4
4
5
5
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.
6
17
7
18
config TASKSET
8
19
bool "taskset"
@@ -29,6 +40,10 @@ config TASKSET
29
40
#define sched_getaffinity (pid , size , cpuset ) \
30
41
syscall(__NR_sched_getaffinity, (pid_t)pid, (size_t)size, (void *)cpuset)
31
42
43
+ GLOBALS (
44
+ int nproc ;
45
+ )
46
+
32
47
// mask is an array of long, which makes the layout a bit weird on big
33
48
// endian systems but as long as it's consistent...
34
49
@@ -104,3 +119,30 @@ void taskset_main(void)
104
119
} else do_taskset (pid , 0 );
105
120
}
106
121
}
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