4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer NETwork research (NET)
6 // Stefan Bund <g0dil@berlios.de>
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 \brief Daemon non-inline non-template implementation */
30 #include <sys/types.h>
38 #include "../Utils/Exception.hh"
39 #include "../Utils/membind.hh"
41 //#include "Daemon.mpp"
43 ///////////////////////////////cc.p////////////////////////////////////////
45 #define LIBC_CALL(fn, args) if (fn args < 0) throwErrno(#fn "()")
46 #define LIBC_CALL_RV(var, fn, args) int var (fn args); if (var < 0) throwErrno(#fn "()")
48 ///////////////////////////////////////////////////////////////////////////
51 prefix_ senf::Daemon::~Daemon()
53 if (! pidfile_.empty())
54 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
57 prefix_ void senf::Daemon::daemonize(bool v)
62 prefix_ bool senf::Daemon::daemon()
67 prefix_ void senf::Daemon::consoleLog(std::string path, StdStream which)
71 int fd (::open(path.c_str(), O_WRONLY | O_APPEND));
73 throwErrno("::open()");
89 prefix_ void senf::Daemon::pidFile(std::string f)
94 prefix_ void senf::Daemon::detach()
97 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
98 LIBC_CALL( ::dup2, (nul, 1) );
99 LIBC_CALL( ::dup2, (nul, 2) );
100 LIBC_CALL( ::close, (nul) );
104 prefix_ int senf::Daemon::start(int argc, char const ** argv)
117 if (! pidfile_.empty() && ! pidfileCreate()) {
118 std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?"
127 catch (std::exception & e) {
128 std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
132 std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
140 ////////////////////////////////////////
143 prefix_ senf::Daemon::Daemon()
144 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
148 ////////////////////////////////////////
151 prefix_ void senf::Daemon::configure()
154 prefix_ void senf::Daemon::main()
161 prefix_ void senf::Daemon::init()
164 prefix_ void senf::Daemon::run()
167 prefix_ void senf::Daemon::fork()
172 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
173 LIBC_CALL( ::dup2, (nul, 0) );
174 LIBC_CALL( ::close, (nul) );
175 LIBC_CALL( ::pipe, (coutpipe) );
176 LIBC_CALL( ::pipe, (cerrpipe) );
178 // We need to block the SIGCHLD signal here so we don't miss it, if the child
182 ::sigemptyset(&cldsig);
183 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
184 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
186 LIBC_CALL_RV( pid, ::fork, () );
191 LIBC_CALL( ::dup2, (coutpipe[1],1) );
192 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
193 LIBC_CALL( ::close, (coutpipe[0]) );
194 LIBC_CALL( ::close, (coutpipe[1]) );
195 LIBC_CALL( ::close, (cerrpipe[0]) );
196 LIBC_CALL( ::close, (cerrpipe[1]) );
197 LIBC_CALL( ::setsid, () );
198 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
202 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
205 LIBC_CALL( ::close, (coutpipe[1]) );
206 LIBC_CALL( ::close, (cerrpipe[1]) );
208 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0]);
214 prefix_ bool senf::Daemon::pidfileCreate()
216 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
217 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
218 // was some race condition, probably over NFS.
220 std::string tempname;
223 char hostname[HOST_NAME_MAX+1];
224 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
225 hostname[HOST_NAME_MAX] = 0;
226 std::stringstream tempname_s;
227 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
228 tempname = tempname_s.str();
233 std::ofstream pidf (tempname.c_str());
234 pidf << ::getpid() << std::endl;
237 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
239 throwErrno("::link()");
243 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
244 LIBC_CALL( ::unlink, (tempname.c_str()) );
245 return s.st_nlink == 2;
248 // pidfile exists. Check, whether the pid in the pidfile still exists.
251 std::ifstream pidf (pidfile_.c_str());
252 if ( ! (pidf >> old_pid)
254 || ::kill(old_pid, 0) >= 0
259 // If we reach this point, the pid file exists but the process mentioned within the
260 // pid file does *not* exists. We assume, the pid file to be stale.
262 // I hope, the following procedure is without race condition: We remove our generated
263 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
264 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
265 // must have already created his hardlink. We then truncate the file and write our pid.
267 LIBC_CALL( ::unlink, (tempname.c_str() ));
268 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
269 if (errno != ENOENT) throwErrno("::link()");
270 // Hmm ... the pidfile mysteriously disappeared ... try again.
276 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
277 if (s.st_nlink != 2) {
278 LIBC_CALL( ::unlink, (tempname.c_str()) );
284 std::ofstream pidf (tempname.c_str());
285 pidf << ::getpid() << std::endl;
288 LIBC_CALL( ::unlink, (tempname.c_str()) );
294 ///////////////////////////////////////////////////////////////////////////
295 // senf::detail::DaemonWatcher
297 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe)
298 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), sigChld_(false),
299 coutForwarder_(coutpipe_, 1, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
300 cerrForwarder_(cerrpipe_, 2, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
303 prefix_ void senf::detail::DaemonWatcher::run()
305 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
306 Scheduler::instance().process();
309 ////////////////////////////////////////
312 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
315 case 1 : coutpipe_ = -1; break;
316 case 2 : cerrpipe_ = -1; break;
319 if (coutpipe_ == -1 && cerrpipe_ == -1) {
321 childDied(); // does not return
322 Scheduler::instance().timeout(
323 Scheduler::instance().eventTime() + ClockService::seconds(1),
324 senf::membind(&DaemonWatcher::childOk, this));
328 prefix_ void senf::detail::DaemonWatcher::sigChld()
331 if (coutpipe_ == -1 && cerrpipe_ == -1)
332 childDied(); // does not return
335 prefix_ void senf::detail::DaemonWatcher::childDied()
338 if (::waitpid(childPid_,&status,0) < 0) throwErrno("::waitpid()");
339 if (WIFSIGNALED(status)) {
340 ::signal(WTERMSIG(status),SIG_DFL);
341 ::kill(::getpid(), WTERMSIG(status));
342 // should not be reached
345 if (WEXITSTATUS(status) == 0)
347 ::_exit(WEXITSTATUS(status));
350 prefix_ void senf::detail::DaemonWatcher::childOk()
352 Scheduler::instance().terminate();
355 ///////////////////////////////////////////////////////////////////////////
356 // senf::detail::DaemonWatcher::Forwarder
358 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, int dst, Callback cb)
359 : src_(src), dst_(dst), cb_(cb)
361 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
365 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
368 Scheduler::instance().remove(src_);
369 if (dst_ != -1 && ! buffer_.empty())
370 Scheduler::instance().remove(dst_);
373 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
378 n = ::read(src_,buf,1024);
380 if (errno != EINTR) throwErrno("::read()");
386 Scheduler::instance().remove(src_);
393 // There was an error writing data -> drop it
396 Scheduler::instance().add(dst_, senf::membind(&Forwarder::writeData, this),
397 Scheduler::EV_WRITE);
398 buffer_.insert(buffer_.end(), buf, buf+n);
401 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event)
403 if (event != Scheduler::EV_WRITE) {
404 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
405 Scheduler::instance().remove(dst_);
407 if (src_ == -1) cb_();
411 int n (buffer_.size() > 1024 ? 1024 : buffer_.size());
412 std::copy(buffer_.begin(), buffer_.begin() + n, buf);
413 int w (::write(dst_, buf, n));
415 if (errno != EINTR) throwErrno("::write()");
418 buffer_.erase(buffer_.begin(), buffer_.begin()+w);
419 if (buffer_.empty()) {
420 Scheduler::instance().remove(dst_);
429 ///////////////////////////////cc.e////////////////////////////////////////
431 //#include "Daemon.mpp"
437 // comment-column: 40
438 // c-file-style: "senf"
439 // indent-tabs-mode: nil
440 // ispell-local-dictionary: "american"
441 // compile-command: "scons -u test"