Skip to content
Repos

mologram

C++ 2.1 KB59 lines Opens in site

Directory Raw Download

#include "mologram/DaemonLauncher.hpp"

#include <cerrno>
#include <fcntl.h>
#include <chrono>
#include <climits>
#include <cstring>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>

#include "mologram/SocketUtil.hpp"

namespace mologram {

std::string DaemonLauncher::daemonPath() {
  char buf[PATH_MAX];
  ssize_t n = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
  if (n <= 0) return "mologramd";
  buf[n] = 0;
  std::string self(buf);
  size_t slash = self.rfind('/');
  return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "mologramd";
}

std::string DaemonLauncher::ensure(const std::string& socketPath, const std::vector<std::string>& extraArgs, const std::function<bool()>& giveUp) {
  int e = 0;
  if (SocketUtil::connectUnix(socketPath, e).valid()) return "";
  std::string exe = daemonPath();
  pid_t pid = ::fork();
  if (pid < 0) return std::string("fork: ") + std::strerror(errno);
  if (pid == 0) {
    ::setsid();
    // Detached from the terminal of the UI: anything the daemon wants to say goes to its log file, never onto the TUI screen.
    int nul = ::open("/dev/null", O_RDWR);
    if (nul >= 0) { ::dup2(nul, 0); ::dup2(nul, 1); ::dup2(nul, 2); if (nul > 2) ::close(nul); }
    std::vector<std::string> args{exe, "--socket", socketPath};
    for (const auto& a : extraArgs) args.push_back(a);
    std::vector<char*> argv;
    for (auto& a : args) argv.push_back(a.data());
    argv.push_back(nullptr);
    ::execv(exe.c_str(), argv.data());
    _exit(127);
  }
  for (;;) {
    if (SocketUtil::connectUnix(socketPath, e).valid()) return "";
    if (giveUp && giveUp()) return "cancelled";
    int status = 0;
    pid_t r = ::waitpid(pid, &status, WNOHANG);
    if (r == pid) {
      // The child ended. If another daemon won the race, the socket answers now.
      if (SocketUtil::connectUnix(socketPath, e).valid()) return "";
      return "mologramd exited before serving the socket (exit " + std::to_string(WIFEXITED(status) ? WEXITSTATUS(status) : -1) + ")";
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
  }
}

} // namespace mologram
26.5ms