-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.cc
80 lines (68 loc) · 2.14 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
#include "daemon.h"
#include "log.h"
#include "config.h"
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sstream>
namespace sylar {
static sylar::Logger::ptr g_logger = SYLAR_LOG_NAME("system");
static sylar::ConfigVar<uint32_t>::ptr g_daemon_restart_interval
= sylar::Config::Lookup("daemon.restart_interval", (uint32_t)5,
"daemon restart interval");
std::string ProcessInfo::toString() const {
std::stringstream ss;
ss << "[ProcessInfo parent_id=" << parent_id
<< " main_id = " << main_id
<< " parent_start_time=" << sylar::Time2Str(parent_start_time)
<< "main_start_time=" << sylar::Time2Str(main_start_time)
<< " restart_count=" << restart_count << "]";
return ss.str();
}
static int real_start(int argc, char** argv
,std::function<int(int argc, char** argv)> main_cb) {
return main_cb(argc, argv);
}
static int real_daemon(int argc, char** argv
,std::function<int(int argc, char** argv)> main_cb) {
daemon(1, 0);
ProcessInfoMgr::GetInstence()->parent_id = getpid();
ProcessInfoMgr::GetInstence()->parent_start_time = time(0);
while(true) {
pid_t pid = fork();
if(pid == 0) {
//子进程返回
ProcessInfoMgr::GetInstence()->main_id = getpid();
ProcessInfoMgr::GetInstence()->main_start_time = time(0);
SYLAR_LOG_INFO(g_logger) << "process start pid=" << getpid();
return real_start(argc, argv, main_cb);
} else if(pid < 0) {
SYLAR_LOG_ERROR(g_logger) << "fork fail return=" << pid
<< " errno=" << errno << " errstr=" << strerror(errno);
return -1;
} else {
//父进程返回
int status = 0;
waitpid(pid, &status, 0);
if(status) {
SYLAR_LOG_ERROR(g_logger) << "child crash pid=" << pid
<< " status=" << status;
} else {
SYLAR_LOG_INFO(g_logger) << "child finished pid=" << pid;
break;
}
ProcessInfoMgr::GetInstence()->restart_count += 1;
sleep(g_daemon_restart_interval->getValue());
}
}
return 0;
}
int start_daemon(int argc, char** argv
,std::function<int(int argc, char** argv)> main_cb
,bool is_daemon) {
if(!is_daemon) {
return real_start(argc, argv, main_cb);
}
return real_daemon(argc, argv, main_cb);
}
}