summaryrefslogtreecommitdiffhomepage
path: root/PIDFile.cpp
blob: 6bfaa3ac46cfe07c86c9acb7bb612ace58e9362d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;
}