cut: shorten error messages on bad syntax even more
[busybox-git.git] / coreutils / nproc.c
blobdf63bf57a326093a4a52960e8fd7bbe102e3ce3c
1 /*
2 * Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com>
4 * Licensed under GPLv2, see LICENSE in this source tree
5 */
6 //config:config NPROC
7 //config: bool "nproc (3.9 kb)"
8 //config: default y
9 //config: help
10 //config: Print number of CPUs
12 //applet:IF_NPROC(APPLET_NOFORK(nproc, nproc, BB_DIR_USR_BIN, BB_SUID_DROP, nproc))
14 //kbuild:lib-$(CONFIG_NPROC) += nproc.o
16 //usage:#define nproc_trivial_usage
17 //usage: ""IF_LONG_OPTS("[--all] [--ignore=N]")
18 //usage:#define nproc_full_usage "\n\n"
19 //usage: "Print number of available CPUs"
20 //usage: IF_LONG_OPTS(
21 //usage: "\n"
22 //usage: "\n --all Number of installed CPUs"
23 //usage: "\n --ignore=N Exclude N CPUs"
24 //usage: )
26 #include "libbb.h"
28 int nproc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
29 int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
31 int count = 0;
32 #if ENABLE_LONG_OPTS
33 int ignore = 0;
34 int opts = getopt32long(argv, "\xfe:+",
35 "ignore\0" Required_argument "\xfe"
36 "all\0" No_argument "\xff"
37 , &ignore
40 if (opts & (1 << 1)) {
41 DIR *cpusd = opendir("/sys/devices/system/cpu");
42 if (cpusd) {
43 struct dirent *de;
44 while (NULL != (de = readdir(cpusd))) {
45 char *cpuid = strstr(de->d_name, "cpu");
46 if (cpuid && isdigit(cpuid[strlen(cpuid) - 1]))
47 count++;
49 IF_FEATURE_CLEAN_UP(closedir(cpusd);)
51 } else
52 #endif
54 int i;
55 unsigned sz = 2 * 1024;
56 unsigned long *mask = get_malloc_cpu_affinity(0, &sz);
57 sz /= sizeof(long);
58 for (i = 0; i < sz; i++) {
59 if (mask[i] != 0) /* most mask[i] are usually 0 */
60 count += bb_popcnt_long(mask[i]);
62 IF_FEATURE_CLEAN_UP(free(mask);)
65 IF_LONG_OPTS(count -= ignore;)
66 if (count <= 0)
67 count = 1;
69 printf("%u\n", count);
71 return 0;