-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnice.cpp
More file actions
55 lines (46 loc) · 1.63 KB
/
nice.cpp
File metadata and controls
55 lines (46 loc) · 1.63 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
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <sys/resource.h>
#include <unistd.h>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "nice",
.version = CFBOX_VERSION_STRING,
.one_line = "run a program with modified scheduling priority",
.usage = "nice [-n ADJUSTMENT] COMMAND [ARGS]...",
.options = " -n ADJUSTMENT add ADJUSTMENT to nice value (default 10)",
.extra = "",
};
} // namespace
auto nice_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'n', true, "adjustment"},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
int adjustment = 10;
if (auto n = parsed.get_any('n', "adjustment")) {
adjustment = std::stoi(std::string{*n});
}
const auto& pos = parsed.positional();
if (pos.empty()) {
CFBOX_ERR("nice", "missing command");
return 1;
}
setpriority(PRIO_PROCESS, 0, getpriority(PRIO_PROCESS, 0) + adjustment);
std::vector<std::string> arg_storage;
arg_storage.reserve(pos.size());
for (auto p : pos) arg_storage.emplace_back(p);
std::vector<char*> cmd_args;
cmd_args.reserve(arg_storage.size() + 1);
for (auto& s : arg_storage) cmd_args.push_back(s.data());
cmd_args.push_back(nullptr);
execvp(cmd_args[0], cmd_args.data());
CFBOX_ERR("nice", "%s: %s", cmd_args[0], std::strerror(errno));
return 127;
}