-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswapoff.cpp
More file actions
82 lines (73 loc) · 2.34 KB
/
Copy pathswapoff.cpp
File metadata and controls
82 lines (73 loc) · 2.34 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
74
75
76
77
78
79
80
81
82
#include <cfbox/args.hpp>
#include <cfbox/error.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cstdio>
#include <cstring>
#include <string>
#include <sys/swap.h>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "swapoff",
.version = CFBOX_VERSION_STRING,
.one_line = "disable swap",
.usage = "swapoff [-a] [DEVICE]",
.options = " -a disable all swap devices listed in /proc/swaps",
.extra = "",
};
// First whitespace-delimited token of a /proc/swaps line (the device path).
auto first_token(const char* line) -> std::string {
std::string dev;
for (const char* p = line; *p && *p != ' ' && *p != '\t' && *p != '\n'; ++p)
dev += *p;
return dev;
}
} // namespace
auto swapoff_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv,
{
cfbox::args::OptSpec{'a', false, "all"},
});
if (parsed.has_long("help")) {
cfbox::help::print_help(HELP);
return 0;
}
if (parsed.has_long("version")) {
cfbox::help::print_version(HELP);
return 0;
}
if (parsed.has('a')) {
// open_file via RAII unique_file (auto-fclose); open failure stays silent
// (no swap configured — nothing to do), matching the prior fopen behavior.
auto opened = cfbox::io::open_file("/proc/swaps", "r");
if (!opened)
return 0;
FILE* f = opened.value().get();
char line[512];
if (!std::fgets(line, sizeof(line), f)) { // skip header; empty swaps file is fine
return 0;
}
int rc = 0;
while (std::fgets(line, sizeof(line), f)) {
std::string dev = first_token(line);
if (dev.empty())
continue;
if (::swapoff(dev.c_str()) != 0) {
CFBOX_ERR("swapoff", "%s: %s", dev.c_str(), std::strerror(errno));
rc = 1;
}
}
return rc;
}
const auto& pos = parsed.positional();
if (pos.empty()) {
cfbox::help::print_help(HELP);
return 2;
}
std::string dev(pos[0]);
if (::swapoff(dev.c_str()) != 0) {
CFBOX_ERR("swapoff", "%s: %s", dev.c_str(), std::strerror(errno));
return 1;
}
return 0;
}