Commit 17bd69cb6c4ab11de7d09de5703e11da7aacddaf

Authored by Jürgen Knödlseder
1 parent 5269ad65

Exit daemon if another daemon holds the lock file

Showing 1 changed file with 20 additions and 3 deletions
src/support/GDaemon.cpp
... ... @@ -47,6 +47,7 @@
47 47 /* __ Macros _____________________________________________________________ */
48 48  
49 49 /* __ Coding definitions _________________________________________________ */
  50 +#define G_APPEND_LOG //!< Append output to log file
50 51  
51 52 /* __ Debug definitions __________________________________________________ */
52 53  
... ... @@ -175,7 +176,11 @@ GDaemon* GDaemon::clone(void) const
175 176 void GDaemon::start(void)
176 177 {
177 178 // Open logger
  179 + #if defined(G_APPEND_LOG)
  180 + m_log.open(gammalib::gamma_filename("daemon.log"), false);
  181 + #else
178 182 m_log.open(gammalib::gamma_filename("daemon.log"), true);
  183 + #endif
179 184 m_log.chatter((GChatter)m_chatter);
180 185 m_log.date(true);
181 186  
... ... @@ -193,6 +198,16 @@ void GDaemon::start(void)
193 198 // Main event handling loop
194 199 while (true) {
195 200  
  201 + // If another daemon is running then exit this daemon
  202 + pid_t pid = lock_pid();
  203 + if (pid != m_pid) {
  204 + m_log << "*** Another daemon with PID " << pid;
  205 + m_log << " is running, while this daemon has PID " << m_pid;
  206 + m_log << ". Exit this daemon.";
  207 + m_log << std::endl;
  208 + break;
  209 + }
  210 +
196 211 // Put all activities into try-catch block
197 212 try {
198 213  
... ... @@ -201,7 +216,8 @@ void GDaemon::start(void)
201 216  
202 217 }
203 218 catch (const std::exception &except) {
204   - m_log << "*** Exception catched by daemon:" << std::endl;
  219 + m_log << "*** Exception catched by daemon with PID " << m_pid;
  220 + m_log << ":" << std::endl;
205 221 m_log << except.what() << std::endl;
206 222 }
207 223  
... ... @@ -214,7 +230,8 @@ void GDaemon::start(void)
214 230 } // endwhile: main event loop
215 231  
216 232 // Log termination of event loop
217   - m_log << "Terminated event loop for unknown reason." << std::endl;
  233 + m_log << "Terminated event loop for daemon with PID " << m_pid;
  234 + m_log << "." << std::endl;
218 235  
219 236 // Delete lock file
220 237 delete_lock_file();
... ... @@ -400,7 +417,7 @@ void GDaemon::delete_lock_file(void)
400 417 std::remove(lockfile.url().c_str());
401 418  
402 419 // Log removal of lock file
403   - m_log << "Removal of lock file \"" << lockfile.url();
  420 + m_log << "Removed lock file \"" << lockfile.url();
404 421 m_log << "\" for PID " << (int)(m_pid) << std::endl;
405 422  
406 423 }
... ...