-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnohup.cpp
More file actions
62 lines (52 loc) · 1.78 KB
/
nohup.cpp
File metadata and controls
62 lines (52 loc) · 1.78 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
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <signal.h>
#include <unistd.h>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "nohup",
.version = CFBOX_VERSION_STRING,
.one_line = "run a command immune to hangups",
.usage = "nohup COMMAND [ARGS]...",
.options = "",
.extra = "Output is appended to nohup.out or $HOME/nohup.out.",
};
} // namespace
auto nohup_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
const auto& pos = parsed.positional();
if (pos.empty()) {
CFBOX_ERR("nohup", "missing command");
return 1;
}
signal(SIGHUP, SIG_IGN);
// Redirect stdout/stderr to nohup.out
std::string outfile = "nohup.out";
if (const char* home = std::getenv("HOME")) {
// Only use $HOME/nohup.out if cwd is not writable
if (access(".", W_OK) != 0) {
outfile = std::string{home} + "/nohup.out";
}
}
auto* f = freopen(outfile.c_str(), "a", stdout);
if (!f) {
CFBOX_ERR("nohup", "cannot open %s: %s", outfile.c_str(), std::strerror(errno));
return 1;
}
dup2(fileno(stdout), STDERR_FILENO);
std::vector<std::string> arg_storage;
for (auto p : pos) arg_storage.emplace_back(p);
std::vector<char*> cmd_args;
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("nohup", "%s: %s", cmd_args[0], std::strerror(errno));
return 127;
}