-
Notifications
You must be signed in to change notification settings - Fork 2
/
daemonize.cpp
282 lines (239 loc) · 6.42 KB
/
daemonize.cpp
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#include "daemonize.h"
#include <cstdio>
#include <cstdlib>
#include <csignal>
#include <iostream>
#ifdef _MSC_VER
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#pragma comment(lib, "advapi32.lib")
SERVICE_STATUS gServiceStatus = { 0 };
SERVICE_STATUS_HANDLE gStatusHandle = nullptr;
#define DEF_PID_PATH ""
#define LOG(msg) {}
#else
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
#include <syslog.h>
#define LOG(msg) { syslog (LOG_NOTICE, msg); }
#define DEF_PID_PATH "/var/run/"
#endif
static std::string serviceName;
static TDaemonRunner daemonRun;
static TDaemonRunner daemonStopRequest;
static TDaemonRunner daemonDone;
#define DEF_FD_LIMIT (1024 * 10)
const char *DEVNULL = "/dev/null";
Daemonize:: Daemonize(
const std::string &daemonName,
const std::string &aWorkingDirectory,
TDaemonRunner runner, ///< function to run as deamon
TDaemonRunner stopRequest, ///< function to stop
TDaemonRunner done, ///< function to clean after runner exit
const int aMaxFileDescriptors, ///< 0- default 1024
const std::string &aPidFileName, ///< if empty, /var/run/program_name.pid is used
const bool aCloseFileDescriptors
)
: workingDirectory(aWorkingDirectory), maxFileDescriptors(aMaxFileDescriptors), closeFileDescriptors(aCloseFileDescriptors)
{
serviceName = daemonName;
if (aPidFileName.empty())
pidFileName = DEF_PID_PATH + daemonName + ".pid";
else
pidFileName = aPidFileName;
daemonRun = runner;
daemonStopRequest = stopRequest;
daemonDone = done;
int r = init();
if (r)
std::cerr << "Error daemonize " << r << std::endl;
}
Daemonize::~Daemonize()
{
}
#ifdef _MSC_VER
void statusStartPending()
{
gServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
gServiceStatus.dwControlsAccepted = 0;
gServiceStatus.dwCurrentState = SERVICE_START_PENDING;
gServiceStatus.dwWin32ExitCode = 0;
gServiceStatus.dwServiceSpecificExitCode = 0;
gServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus(gStatusHandle, &gServiceStatus) == FALSE)
{
OutputDebugString(_T(
"ServiceMain: SetServiceStatus returned error"));
}
}
void statusStarted()
{
gServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
gServiceStatus.dwCurrentState = SERVICE_RUNNING;
gServiceStatus.dwWin32ExitCode = 0;
gServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus(gStatusHandle, &gServiceStatus) == FALSE)
{
OutputDebugString(_T(
"ServiceMain: SetServiceStatus returned error"));
}
}
void statusStopPending()
{
gServiceStatus.dwControlsAccepted = 0;
gServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
gServiceStatus.dwWin32ExitCode = 0;
gServiceStatus.dwCheckPoint = 4;
if (SetServiceStatus(gStatusHandle, &gServiceStatus) == FALSE)
{
OutputDebugString(_T(
"ServiceCtrlHandler: SetServiceStatus returned error"));
}
}
void statusStopped()
{
gServiceStatus.dwControlsAccepted = 0;
gServiceStatus.dwCurrentState = SERVICE_STOPPED;
gServiceStatus.dwWin32ExitCode = 0;
gServiceStatus.dwCheckPoint = 3;
if (SetServiceStatus(gStatusHandle, &gServiceStatus) == FALSE)
{
OutputDebugString(_T(
"ServiceMain: SetServiceStatus returned error"));
}
}
VOID WINAPI ServiceCtrlHandler(DWORD CtrlCode)
{
switch (CtrlCode) {
case SERVICE_CONTROL_STOP:
if (gServiceStatus.dwCurrentState != SERVICE_RUNNING)
break;
statusStopPending();
daemonStopRequest();
daemonDone();
statusStopped();
break;
default:
break;
}
}
VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{
// Register our service control handler with the SCM
gStatusHandle = RegisterServiceCtrlHandlerA((LPCSTR) serviceName.c_str(), ServiceCtrlHandler);
if (gStatusHandle == nullptr)
goto EXIT;
// Tell the service controller we are starting
ZeroMemory(&gServiceStatus, sizeof(gServiceStatus));
statusStartPending();
// Tell the service controller we are started
statusStarted();
daemonRun();
daemonDone();
// Tell the service controller we are stopped
statusStopped();
EXIT:
return;
}
// See http://stackoverflow.com/questions/18557325/how-to-create-windows-service-in-c-c
int Daemonize::init()
{
std::wstring sn(serviceName.begin(), serviceName.end());
SERVICE_TABLE_ENTRY ServiceTable[] = {
{(LPSTR) sn.c_str(), (LPSERVICE_MAIN_FUNCTION) ServiceMain},
{nullptr, nullptr}
};
if (StartServiceCtrlDispatcher (ServiceTable) == FALSE)
return GetLastError();
return 0;
}
int Daemonize::setFdLimit(int value)
{
return 0;
}
bool Daemonize::setPidFile()
{
return true;
}
#else
//See http://stackoverflow.com/questions/17954432/creating-a-daemon-in-linux
int Daemonize::init()
{
pid_t pid;
// Fork off the parent process
pid = fork();
// An error occurred
if (pid < 0)
exit(EXIT_FAILURE);
// Success: Let the parent terminate
if (pid > 0)
exit(EXIT_SUCCESS);
// On success: The child process becomes session leader
if (setsid() < 0)
exit(EXIT_FAILURE);
// Catch, ignore and handle signals
//TODO: Implement a working signal handler */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
// Fork off for the second time
pid = fork();
// An error occurred
if (pid < 0)
exit(EXIT_FAILURE);
// Success: Let the parent terminate
if (pid > 0)
exit(EXIT_SUCCESS);
// Set new file permissions
umask(0);
int x;
// Change the working directory to the root directory
// or another appropriated directory
x = chdir(workingDirectory.c_str());
// Close all open file descriptors
if (closeFileDescriptors) {
for (x = sysconf(_SC_OPEN_MAX); x>0; x--) {
if (x > 2)
close(x);
}
// reopen stdin, stdout, stderr
/*
stdin = fopen(DEVNULL, "r");
stdout = fopen(DEVNULL, "w+");
stderr = fopen(DEVNULL, "w+");
*/
}
if (maxFileDescriptors > 0)
setFdLimit(maxFileDescriptors);
setPidFile();
daemonRun();
daemonDone();
return 0;
}
/**
* Set
* @param value file descriptors per process. Default 1024 on Linux
* @return 0- success
*/
int Daemonize::setFdLimit(int value)
{
struct rlimit lim;
int status;
// current limit
lim.rlim_cur = value;
// max limit
lim.rlim_max = value;
return setrlimit(RLIMIT_NOFILE, &lim);
}
bool Daemonize::setPidFile()
{
FILE* f = fopen(pidFileName.c_str(), "w+");
if (f) {
fprintf(f, "%u", getpid());
fclose(f);
return true;
}
return false;
}
#endif