Toolbox
snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
toolbox
sys
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
23
namespace
toolbox
{
24
inline
namespace
sys {
25
using namespace
std
;
26
27
void
close_all
()
noexcept
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
36
void
daemon
()
37
{
38
pid_t
pid
{
os::fork
()};
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
Daemon.hpp
System.hpp
std
STL namespace.
toolbox::hdr::min
int64_t min(const Histogram &h) noexcept
Definition
Utility.cpp:41
toolbox::os::fork
pid_t fork()
Create a child process.
Definition
System.hpp:56
toolbox::os::setsid
pid_t setsid()
Creates a session and sets the process group ID.
Definition
System.hpp:76
toolbox::sys::daemon
void daemon()
Daemonise process. Detach from controlling terminal and run in the background as a system daemon.
Definition
Daemon.cpp:36
toolbox::sys::close_all
void close_all() noexcept
Close all non-standard file handles.
Definition
Daemon.cpp:27
toolbox::sys::make_error
std::error_code make_error(int err) noexcept
Definition
Error.hpp:25
toolbox::util::bind
constexpr auto bind() noexcept
Definition
Slot.hpp:92
toolbox
Definition
Benchmark.cpp:26
Generated by
1.9.8