libmoost
|
00001 /* vim:set ts=3 sw=3 sts=3 et: */ 00028 #ifndef MOOST_PROCESS_DAEMON_HPP__ 00029 #define MOOST_PROCESS_DAEMON_HPP__ 00030 00031 #include <boost/function.hpp> 00032 #include <boost/thread.hpp> 00033 00034 #include "detail/daemon_linux.hpp" 00035 00036 namespace moost { namespace process { 00037 00046 class daemon 00047 { 00048 private: 00049 struct default_child_init_func 00050 { 00051 bool operator()() { return false; } 00052 }; 00053 00054 public: 00070 daemon(bool exit_parent, boost::function0<bool> child_init_func) 00071 { 00072 init(exit_parent, child_init_func); 00073 } 00074 00085 daemon(bool exit_parent) 00086 { 00087 init(exit_parent, default_child_init_func()); 00088 } 00089 00104 daemon(boost::function0<bool> child_init_func) 00105 { 00106 init(true, child_init_func); 00107 } 00108 00115 pid_t get_pid() const { return daemon_impl_.get_pid_(); } 00116 00123 bool is_child() const { return 0 == get_pid(); } 00124 00131 bool is_parent() const { return !is_child(); } 00132 00141 static void sleep_forever() 00142 { 00143 for(;;) 00144 { 00145 // Never again shall this thread awaken from a deep slumber :) 00146 boost::this_thread::sleep( 00147 boost::posix_time::time_duration(boost::posix_time::pos_infin) 00148 ); 00149 } 00150 } 00151 00152 private: 00153 void init(bool exit_parent, boost::function0<bool> child_init_func) 00154 { 00155 daemon_impl_.fork_(child_init_func); 00156 00157 if(exit_parent && is_parent()) 00158 { 00159 exit(EXIT_SUCCESS); 00160 } 00161 } 00162 00163 private: 00164 daemon_impl daemon_impl_; 00165 }; 00166 00167 }} 00168 00169 00170 #endif // MOOST_PROCESS_DAEMON_HPP__