-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpidof.cpp
More file actions
61 lines (53 loc) · 1.66 KB
/
pidof.cpp
File metadata and controls
61 lines (53 loc) · 1.66 KB
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
#include <cstdio>
#include <string>
#include <string_view>
#include <cfbox/applet.hpp>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/proc.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "pidof",
.version = CFBOX_VERSION_STRING,
.one_line = "find the process ID of a running program",
.usage = "pidof [-s] NAME...",
.options = " -s single shot — return one PID only",
.extra = "",
};
} // anonymous namespace
auto pidof_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'s', false, "single"},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
bool single = parsed.has('s') || parsed.has_long("single");
const auto& names = parsed.positional();
if (names.empty()) {
CFBOX_ERR("pidof", "no program name specified");
return 1;
}
auto result = cfbox::proc::read_all_processes();
if (!result) {
CFBOX_ERR("pidof", "%s", result.error().msg.c_str());
return 1;
}
bool found = false;
bool first = true;
for (const auto& proc : *result) {
for (const auto& name : names) {
if (proc.comm == name) {
if (!first) std::printf(" ");
std::printf("%d", proc.pid);
first = false;
found = true;
if (single) goto done;
break;
}
}
}
done:
if (found) std::printf("\n");
return found ? 0 : 1;
}