Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
PidFile.cpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2021 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#include "PidFile.hpp"
18
19#include "Error.hpp"
20
22
23#include <toolbox/contrib/flopen.c>
24#include <toolbox/contrib/pidfile.c>
25
26// Note that it is safe to pass null to the pidfile_write(), pidfile_remove() and pidfile_close()
27// functions.
28
29namespace toolbox {
30inline namespace sys {
31using namespace std::literals::string_literals;
32
37
38PidFile open_pid_file(const char* path, mode_t mode)
39{
40 pid_t pid{};
41 PidFile pf{pidfile_open(path, mode, &pid)};
42 if (!pf) {
43 if (errno == EEXIST) {
44 throw std::runtime_error{"daemon already running, pid: "s + to_string(pid)};
45 }
46 throw std::system_error{make_error(errno), "pidfile_open"};
47 }
48 return pf;
49}
50
51void close_pid_file(PidFile& pf) noexcept
52{
53 if (pf) {
54 pidfile_close(pf.release());
55 }
56}
57
59{
60 if (pf && pidfile_write(pf.get()) < 0) {
61 throw std::system_error{make_error(errno), "pidfile_write"};
62 }
63}
64
65} // namespace sys
66} // namespace toolbox
void close_pid_file(PidFile &pf) noexcept
Close pidfile without removing it. This function should be used when forking daemon processes.
Definition PidFile.cpp:51
std::unique_ptr< pidfh, detail::PidFileDeleter > PidFile
Definition PidFile.hpp:34
std::error_code make_error(int err) noexcept
Definition Error.hpp:25
void write_pid_file(PidFile &pf)
Write process' PID into pidfile.
Definition PidFile.cpp:58
PidFile open_pid_file(const char *path, mode_t mode)
Definition PidFile.cpp:38
std::string to_string(ValueT &&val)
Definition String.hpp:54
constexpr auto bind() noexcept
Definition Slot.hpp:92
void operator()(pidfh *pfh) const noexcept
Definition PidFile.cpp:33