From 3c7b85d8355c64dec5b4ce011753196d53774103 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Sat, 11 Jan 2025 10:36:20 +0100 Subject: Added PIDFile --- PIDFile.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 PIDFile.cpp (limited to 'PIDFile.cpp') diff --git a/PIDFile.cpp b/PIDFile.cpp new file mode 100644 index 0000000..85f30d3 --- /dev/null +++ b/PIDFile.cpp @@ -0,0 +1,54 @@ +#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; +} + -- cgit v1.2.3