12#include <shared_mutex>
20namespace platf::bounded_command {
29 static std::shared_mutex mutex;
33 inline std::optional<std::string> output(
const std::string &command, std::chrono::milliseconds timeout,
bool *timed_out) {
34 std::shared_lock reap_lock {reap_mutex()};
39 if (::pipe2(out, O_CLOEXEC) != 0) {
42 const pid_t child = ::fork();
52 ::dup2(out[1], STDOUT_FILENO);
53 ::execl(
"/bin/sh",
"sh",
"-c",
command.c_str(),
static_cast<char *
>(
nullptr));
56 ::setpgid(child, child);
60 std::array<char, 4096> buffer {};
61 const auto deadline = std::chrono::steady_clock::now() +
timeout;
62 bool pipe_open =
true;
66 while (pipe_open || !exited) {
67 if (std::chrono::steady_clock::now() >= deadline) {
74 pollfd readable {out[0], POLLIN, 0};
75 const int ready = ::poll(&readable, 1, exited ? 0 : 20);
77 const ssize_t got = ::read(out[0], buffer.data(), buffer.size());
79 output.append(buffer.data(),
static_cast<size_t>(got));
80 }
else if (got == 0 || errno != EINTR) {
83 }
else if (exited && ready == 0) {
87 std::this_thread::sleep_for(std::chrono::milliseconds {10});
90 const pid_t reaped = ::waitpid(child, &status, WNOHANG);
91 if (reaped == child) {
93 }
else if (reaped < 0 && errno != EINTR) {
102 ::kill(-child, SIGKILL);
103 ::kill(child, SIGKILL);
108 const auto reap_deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds {100};
110 const auto reaped = ::waitpid(child, &status, WNOHANG);
111 if (reaped == child || (reaped < 0 && errno != EINTR)) {
114 std::this_thread::sleep_for(std::chrono::milliseconds {1});
115 }
while (std::chrono::steady_clock::now() < reap_deadline);
122 if (status == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
std::shared_mutex & reap_mutex()
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.