#include "PIDFile.h" #include "log.h" #include #include #include #include #include "unistd.h" namespace fs = std::filesystem; PIDFile::PIDFile(const std::string& programname): m_programname{programname} { pid_t pid{getpid()}; std::string contents{std::to_string(static_cast(pid))}; fs::path filename{get_filename()}; if (fs::exists(filename)) { pid_t existing_pid{get_pid_from_file()}; if (Reichwein::Process::is_running(existing_pid)) { throw std::runtime_error(fmt::format("Program already running at PID {}", existing_pid)); } else { log_cout << fmt::format("Found stale PID file {}, removing.\n", filename.string()); } } try { Reichwein::File::setFile(filename, contents); } catch (const std::exception& ex) { log_cout << fmt::format("Warning: Not able to write to file{}, ignoring.\n", filename.string()); } } PIDFile::~PIDFile() { fs::remove(get_filename()); } int PIDFile::get_pid_from_file() const { std::string contents{Reichwein::File::getFile(get_filename())}; return std::stoul(contents); } fs::path PIDFile::get_filename() const { return fs::path{"/var/run"} / m_programname; }