31{
32
33
34
35
36
37
38 std::ofstream pidofs;
39 if (! pidfile.empty ())
40 {
41 int oldpid;
42 std::ifstream pidrifs;
43 pidrifs.open(pidfile, std::fstream::in);
44 if (! pidrifs.fail())
45 {
46
47 if (pidrifs >> oldpid && oldpid > 1 && kill(oldpid, 0) == 0)
48 {
49 quit("PID file " + pidfile + " already exists and the PID therein is valid");
50 }
51 pidrifs.close();
52 }
53
54 pidofs.open(pidfile, std::fstream::out | std::fstream::trunc);
55 if (pidofs.fail())
56 {
57 quit("Failed to open specified PID file for writing");
58 }
59 }
60
61
62
64 {
65 if (pid > 0)
66 {
67
68 pidofs.close();
69
70
71
72 exit(0);
73 }
74 else
75 {
76 quit("First fork failed");
77 }
78 }
79
80
81
82 setsid();
83
84
86 {
87 if (pid > 0)
88 {
89 pidofs.close();
90 exit(0);
91 }
92 else
93 {
94 quit("Second fork failed");
95 }
96 }
97
98 if (! pidofs.fail())
99 {
100 int pid = ::getpid();
101 pidofs << pid << std::endl;
102 pidofs.close();
103 }
104
105
106
107 close(0);
108 close(1);
109 close(2);
110
111
112 if (open("/dev/null", O_RDONLY) < 0)
113 {
114 quit("Unable to open /dev/null");
115 }
116
117#ifdef DEBUG_TMPDIR_LOG
118
119 const char *tmpdir = getenv("TMPDIR");
120 if (!tmpdir)
122 std::string output = tmpdir;
123 output += "/electroneum.daemon.stdout.stderr";
124 const int flags = O_WRONLY | O_CREAT | O_APPEND;
125 const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
126 if (open(output.c_str(), flags, mode) < 0)
127 {
128 quit("Unable to open output file: " + output);
129 }
130
131
132 if (dup(1) < 0)
133 {
134 quit("Unable to dup output descriptor");
135 }
136#endif
137}
void fork(const std::string &pidfile)