diff options
author | Roland Reichwein <mail@reichwein.it> | 2025-01-11 10:36:20 +0100 |
---|---|---|
committer | Roland Reichwein <mail@reichwein.it> | 2025-01-11 10:36:20 +0100 |
commit | 3c7b85d8355c64dec5b4ce011753196d53774103 (patch) | |
tree | b350ef977987dd5e4155ae71d2c836a762225d56 /PIDFile.cpp | |
parent | aa210ed8a27387882fc7fd0dcd7cf961a9adc88f (diff) |
Added PIDFile
Diffstat (limited to 'PIDFile.cpp')
-rw-r--r-- | PIDFile.cpp | 54 |
1 files changed, 54 insertions, 0 deletions
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 <libreichwein/file.h> +#include <libreichwein/process.h> +#include <fmt/format.h> + +#include <stdexcept> + +#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<int>(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; +} + |