Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Daemon.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 "Daemon.hpp"
18
19#include "System.hpp"
20
21#include <fcntl.h> // open()
22
23namespace toolbox {
24inline namespace sys {
25using namespace std;
26
28{
29 // Impose upper bound because Docker containers may have a very large default.
30 const int fds{min(getdtablesize(), 1024)};
31 for (int fd{STDERR_FILENO + 1}; fd < fds; ++fd) {
32 close(fd);
33 }
34}
35
36void daemon()
37{
39 if (pid != 0) {
40 // Exit parent process using system version of exit() to avoid flushing standard streams.
41 // FIXME: use quick_exit() when available on OSX.
42 _exit(0);
43 }
44
45 // Detach from controlling terminal by making process a session leader.
46 os::setsid();
47
48 // Forking again ensures that the daemon process is not a session leader, and therefore cannot
49 // regain access to a controlling terminal.
50 pid = os::fork();
51 if (pid != 0) {
52 // FIXME: use quick_exit() when available on OSX.
53 _exit(0);
54 }
55
56 // Re-open standard input.
57 close(STDIN_FILENO);
58 const auto fd = ::open("/dev/null", O_RDONLY);
59 if (fd < 0) {
60 throw std::system_error{make_error(errno), "open"};
61 }
62}
63
64} // namespace sys
65} // namespace toolbox
STL namespace.
int64_t min(const Histogram &h) noexcept
Definition Utility.cpp:41
pid_t fork()
Create a child process.
Definition System.hpp:56
pid_t setsid()
Creates a session and sets the process group ID.
Definition System.hpp:76
void daemon()
Daemonise process. Detach from controlling terminal and run in the background as a system daemon.
Definition Daemon.cpp:36
void close_all() noexcept
Close all non-standard file handles.
Definition Daemon.cpp:27
std::error_code make_error(int err) noexcept
Definition Error.hpp:25
constexpr auto bind() noexcept
Definition Slot.hpp:92