libmoost
|
00001 /* vim:set ts=3 sw=3 sts=3 et: */ 00028 #ifndef MOOST_PROCESS_PIDFILE_HPP__ 00029 #define MOOST_PROCESS_PIDFILE_HPP__ 00030 00031 #include <boost/filesystem.hpp> 00032 00033 #include <string> 00034 #include <fstream> 00035 00036 namespace moost { namespace process { 00037 00045 class pidfile 00046 { 00047 public: 00063 pidfile( 00064 pid_t const pid, 00065 std::string const & process_name, 00066 boost::filesystem::path const & rundir 00067 ) 00068 : pid_(pid), filepath_((rundir.empty() ? get_default_rundir() : rundir) / (process_name + ".pid")) 00069 { 00070 if(!create()) 00071 { 00072 throw std::runtime_error("failed to create pid file"); 00073 } 00074 } 00075 00086 explicit pidfile( 00087 std::string const & process_name, 00088 boost::filesystem::path const & rundir 00089 ) 00090 : pid_(-1), filepath_((rundir.empty() ? get_default_rundir() : rundir) / (process_name + ".pid")) 00091 { 00092 } 00093 00107 pidfile( 00108 pid_t const pid, 00109 boost::filesystem::path const & filepath 00110 ) 00111 : pid_(pid), filepath_(filepath) 00112 { 00113 if(!create()) 00114 { 00115 throw std::runtime_error("failed to create pid file"); 00116 } 00117 } 00118 00127 explicit pidfile( 00128 boost::filesystem::path const & filepath 00129 ) 00130 : pid_(-1), filepath_(filepath) 00131 { 00132 } 00133 00140 ~pidfile() 00141 { 00142 try 00143 { 00144 remove(); 00145 } 00146 catch(...) {} 00147 } 00148 00158 bool create() const 00159 { 00160 if(pid_ == -1) 00161 { 00162 throw std::runtime_error("Cannot create a pid file until the pid is set."); 00163 } 00164 00165 remove(); // just in case there is a rogue file 00166 00167 std::ofstream out(filepath_.string().c_str()); 00168 out << pid_; 00169 return out.good(); 00170 } 00171 00180 bool create(pid_t const pid) 00181 { 00182 pid_ = pid; 00183 return create(); 00184 } 00185 00192 bool remove() const 00193 { 00194 return boost::filesystem::remove(filepath_); 00195 } 00196 00197 00205 static boost::filesystem::path get_default_rundir() 00206 { 00207 return "/var/run"; 00208 } 00209 00210 00211 private: 00212 pid_t pid_; 00213 boost::filesystem::path filepath_; 00214 }; 00215 00216 }} 00217 00218 00219 #endif // MOOST_PROCESS_PIDFILE_HPP__