1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
/*
* Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see LICENSE in this source tree
*/
//config:config NPROC
//config: bool "nproc (3.7 kb)"
//config: default y
//config: help
//config: Print number of CPUs
//applet:IF_NPROC(APPLET_NOFORK(nproc, nproc, BB_DIR_USR_BIN, BB_SUID_DROP, nproc))
//kbuild:lib-$(CONFIG_NPROC) += nproc.o
//usage:#define nproc_trivial_usage
//usage: ""IF_LONG_OPTS("[--all] [--ignore=N]")
//usage:#define nproc_full_usage "\n\n"
//usage: "Print number of available CPUs"
//usage: IF_LONG_OPTS(
//usage: "\n"
//usage: "\n --all Number of installed CPUs"
//usage: "\n --ignore=N Exclude N CPUs"
//usage: )
#include <sched.h>
#include "libbb.h"
int nproc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
{
#if !ENABLE_PLATFORM_MINGW32
unsigned long mask[1024];
#else
DWORD_PTR affinity, process_affinity, system_affinity;
#endif
int count = 0;
#if ENABLE_LONG_OPTS
int ignore = 0;
int opts = getopt32long(argv, "\xfe:+",
"ignore\0" Required_argument "\xfe"
"all\0" No_argument "\xff"
, &ignore
);
#endif
#if !ENABLE_PLATFORM_MINGW32
#if ENABLE_LONG_OPTS
if (opts & (1 << 1)) {
DIR *cpusd = opendir("/sys/devices/system/cpu");
if (cpusd) {
struct dirent *de;
while (NULL != (de = readdir(cpusd))) {
char *cpuid = strstr(de->d_name, "cpu");
if (cpuid && isdigit(cpuid[strlen(cpuid) - 1]))
count++;
}
IF_FEATURE_CLEAN_UP(closedir(cpusd);)
}
} else
#endif
if (sched_getaffinity(0, sizeof(mask), (void*)mask) == 0) {
int i;
for (i = 0; i < ARRAY_SIZE(mask); i++) {
unsigned long m = mask[i];
while (m) {
if (m & 1)
count++;
m >>= 1;
}
}
}
#else /* ENABLE_PLATFORM_MINGW32 */
if (GetProcessAffinityMask(GetCurrentProcess(), &process_affinity,
&system_affinity)) {
affinity = (ENABLE_LONG_OPTS && opts & (1 << 1)) ?
system_affinity : process_affinity;
while (affinity) {
count += affinity & 1;
affinity >>= 1;
}
}
#endif /* ENABLE_PLATFORM_MINGW32 */
IF_LONG_OPTS(count -= ignore;)
if (count <= 0)
count = 1;
printf("%u\n", count);
return 0;
}
|