00001 /* alarm.cc 00002 */ 00003 #include "osl/misc/alarm.h" 00004 #include "osl/misc/lightMutex.h" 00005 #include <stdexcept> 00006 #include <iostream> 00007 #include <cassert> 00008 #include <signal.h> 00009 #include <unistd.h> 00010 00011 volatile int * volatile osl::misc::Alarm::notify = 0; 00012 static osl::LightMutex alarm_mutex; 00013 00014 void osl::misc:: 00015 Alarm::catchSignal(int 00016 #ifndef NDEBUG 00017 signum 00018 #endif 00019 ) 00020 { 00021 assert(SIGALRM == signum); 00022 if (notify) 00023 *notify = TIMEOUT; 00024 notify = 0; 00025 #ifdef DEBUG 00026 const time_t now = time(0); 00027 char ctime_buf[64]; 00028 std::cerr << "\asignal alarm " << ctime_r(&now, ctime_buf); 00029 #endif 00030 } 00031 00032 bool osl::misc:: 00033 Alarm::set(int timeout, AlarmSwitch notify) 00034 { 00035 assert(notify.notify); 00036 assert(timeout > 0); 00037 if (timeout <= 0) 00038 throw std::range_error("negative or zero seconds in Alarm::set"); 00039 LightMutex::scoped_lock lk(alarm_mutex); 00040 if (Alarm::notify) 00041 { 00042 std::cerr << "Alarm reject " << notify.notify << " (" << Alarm::notify << ")" << "\n"; 00043 *notify.notify = UNAVAILABLE; 00044 return false; 00045 } 00046 if (*notify.notify == TIMEOUT) 00047 { 00048 std::cerr << "Alarm::set leave already timeout flag\n"; 00049 return false; 00050 } 00051 Alarm::notify = notify.notify; 00052 signal(SIGALRM, catchSignal); 00053 alarm(timeout); 00054 *notify.notify = WATCHING; 00055 return true; 00056 } 00057 00058 void osl::misc:: 00059 Alarm::reset(AlarmSwitch notify) 00060 { 00061 LightMutex::scoped_lock lk(alarm_mutex); 00062 if (Alarm::notify && notify.notify != Alarm::notify) 00063 { 00064 std::cerr << "warning: Alarm::reset inconsistency " 00065 << const_cast<int*>(notify.notify) << " " << const_cast<int*>(Alarm::notify) << "\n"; 00066 return; 00067 } 00068 Alarm::notify = 0; 00069 alarm(0); 00070 } 00071 00072 00073 /* ------------------------------------------------------------------------- */ 00074 // ;;; Local Variables: 00075 // ;;; mode:c++ 00076 // ;;; c-basic-offset:2 00077 // ;;; End: