watchdog.c

Go to the documentation of this file.
00001 
00008 #ifndef CTL_UNIT
00009 #include "ctl/ctldef.h"
00010 #include "ctl/watchdog.h"
00011 #ifdef WIN32
00012 #include "ctl/mstime.h"
00013 #include <windows.h>
00014 #include <process.h>
00015 #else
00016 #include <unistd.h>
00017 #include <signal.h>
00018 #endif
00019 void ctl_watchdog_handler_default(void)
00020 {
00021     LOG( LOG_ERROR, "Watchdog Elapsed\n" );
00022     assert( !isdebugging() );
00023 }
00024 static ctl_watchdog_handler wd_handler = ctl_watchdog_handler_default;
00025 
00026 #ifdef WIN32
00027 static mstime msexpire = 0;     /* Expiration time; 0 to kill watchdog*/
00028 static HANDLE hThread = NULL;
00029 static HANDLE hSleepy = NULL;
00030 static void WatchdogThreadProc( void* ignored )
00031 {
00032     while( 0 != msexpire )
00033     {
00034         mstime current = ctl_mstime();
00035         mstime expire = msexpire;
00036         if( current > expire )
00037         {
00038             wd_handler();
00039             break;
00040         }
00041         {
00042             WaitForSingleObject( hSleepy, (DWORD)(expire-current) );
00043         }
00044     }
00045     _endthread();
00046 }
00047 #else
00048 static void sigalrm_callback( int sig )
00049 {
00050     wd_handler();
00051 }
00052 #endif
00053 
00059 ctl_watchdog_handler ctl_watchdog_init( ctl_watchdog_handler handler )
00060 {
00061     ctl_watchdog_handler old = wd_handler;
00062     wd_handler = NULL == handler ? ctl_watchdog_handler_default : handler;
00063     assertcodeptr(wd_handler);
00064 #ifdef WIN32
00065     msexpire = ctl_mstime() + 60000;
00066     hSleepy = CreateEvent( NULL, FALSE, FALSE, NULL );
00067     hThread = (HANDLE)_beginthread( WatchdogThreadProc, 0, NULL );
00068 #else
00069     {   /* Assume POSIX */
00070         struct sigaction action;
00071         action.sa_handler = sigalrm_callback;
00072         sigemptyset(&action.sa_mask);
00073         action.sa_flags = 0;
00074         /* alarm() is our watchdog */
00075         sigaction(SIGALRM, &action, NULL);
00076     }
00077     alarm(60);
00078 #endif
00079     return old;
00080 }
00081 
00087 void ctl_watchdog_kick( int milliseconds )
00088 {
00089 #ifdef WIN32
00090     msexpire = ctl_mstime() + milliseconds;
00091     SetEvent( hSleepy );
00092 #else
00093     alarm((milliseconds+999)/1000);
00094 #endif
00095 }
00096 
00100 void ctl_watchdog_shutdown()
00101 {
00102 #ifdef WIN32
00103     msexpire = 0;
00104     SetEvent( hSleepy );
00105     WaitForSingleObject( hThread, INFINITE );
00106     CloseHandle(hSleepy);
00107     hSleepy = NULL;
00108 #else
00109     alarm(0);
00110 #endif
00111 }
00112 #else /* CTL_UNIT */
00113 #endif /* CTL_UNIT */

Generated on Fri Jan 2 15:28:35 2009 for Squat by  doxygen 1.5.6