-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenice.cpp
More file actions
73 lines (61 loc) · 2.29 KB
/
renice.cpp
File metadata and controls
73 lines (61 loc) · 2.29 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
62
63
64
65
66
67
68
69
70
71
72
73
#include <cstdio>
#include <cstring>
#include <string>
#include <sys/resource.h>
#include <unistd.h>
#include <cfbox/applet.hpp>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "renice",
.version = CFBOX_VERSION_STRING,
.one_line = "alter priority of running processes",
.usage = "renice [-n INCREMENT] {-p PID|-g PGRP|-u USER}...",
.options = " -n N increment (default 1)\n"
" -p interpret args as PIDs (default)\n"
" -g interpret args as process groups\n"
" -u interpret args as user names/IDs",
.extra = "",
};
} // anonymous namespace
auto renice_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'n', true, "priority"},
cfbox::args::OptSpec{'p', false, "pid"},
cfbox::args::OptSpec{'g', false, "pgrp"},
cfbox::args::OptSpec{'u', false, "user"},
});
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 increment = 1;
if (auto v = parsed.get('n')) increment = std::stoi(std::string(*v));
const auto& args = parsed.positional();
if (args.empty()) {
CFBOX_ERR("renice", "no ID specified");
return 1;
}
int rc = 0;
for (const auto& id_str : args) {
auto id = static_cast<id_t>(std::stoi(std::string(id_str)));
int which = PRIO_PROCESS;
if (parsed.has('g') || parsed.has_long("pgrp")) which = PRIO_PGRP;
if (parsed.has('u') || parsed.has_long("user")) which = PRIO_USER;
errno = 0;
auto current = getpriority(which, id);
if (errno != 0) {
CFBOX_ERR("renice", "%d: %s", static_cast<int>(id), std::strerror(errno));
rc = 1;
continue;
}
auto new_pri = current + increment;
if (setpriority(which, id, new_pri) != 0) {
CFBOX_ERR("renice", "%d: %s", static_cast<int>(id), std::strerror(errno));
rc = 1;
} else {
std::printf("%d: old priority %d, new priority %d\n", static_cast<int>(id), current, new_pri);
}
}
return rc;
}