-
Notifications
You must be signed in to change notification settings - Fork 256
/
daemon.cc
98 lines (83 loc) · 2.57 KB
/
daemon.cc
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
BAREOS® - Backup Archiving REcovery Open Sourced
Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
Copyright (C) 2013-2022 Bareos GmbH & Co. KG
This program is Free Software; you can redistribute it and/or
modify it under the terms of version three of the GNU Affero General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
/*
* daemon.c by Kern Sibbald 2000
*
* This code is inspired by the Prentice Hall book
* "Unix Network Programming" by W. Richard Stevens
* and later updated from his book "Advanced Programming
* in the UNIX Environment"
*
* Initialize a daemon process completely detaching us from
* any terminal processes.
*/
#include "include/bareos.h"
#include "lib/berrno.h"
#include "lib/daemon.h"
#if defined(HAVE_WIN32)
void daemon_start([[maybe_unused]] const char* progname,
[[maybe_unused]] int pidfile_fd,
[[maybe_unused]] std::string pidfile_path)
{
return;
}
#else // !HAVE_WIN32
# if defined(DEVELOPER)
static void SetupStdFileDescriptors() {}
# else
static void SetupStdFileDescriptors()
{
extern int debug_level;
if (debug_level > 0) { return; }
int fd = open("/dev/null", O_RDONLY);
ASSERT(fd > STDERR_FILENO);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
}
# endif // DEVELOPER
void daemon_start(const char* progname,
int pidfile_fd,
std::string pidfile_path)
{
Dmsg0(900, "Enter daemon_start\n");
switch (fork()) {
case 0:
setsid();
umask(umask(0) | S_IWGRP | S_IROTH | S_IWOTH);
if (!pidfile_path.empty()) {
WritePidFile(pidfile_fd, pidfile_path.c_str(), progname);
}
SetupStdFileDescriptors();
break;
case -1: {
BErrNo be;
Emsg1(M_ABORT, 0, _("Cannot fork to become daemon: ERR=%s\n"),
be.bstrerror());
break;
}
default:
exit(0);
}
Dmsg0(900, "Exit daemon_start\n");
}
#endif /* defined(HAVE_WIN32) */