00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "Watchdog.hxx"
00023
00024 #include <pthread.h>
00025 #include <unistd.h>
00026 #include <cstdio>
00027 #include <cstdlib>
00028
00029 namespace CLAM {
00030
00031
00032 sig_atomic_t Watchdog::mBeat = 0;
00033 unsigned int Watchdog::mQuantumTime = 5;
00034 bool Watchdog::mStarted = false;
00035 bool Watchdog::mVerbose = false;
00036
00037 void *Watchdog::BeatThread(void*)
00038 {
00039 setuid(getuid());
00040
00041 while(1)
00042 {
00043 sleep(mQuantumTime);
00044 if (mBeat != 1)
00045 {
00046 mBeat = 1;
00047 }
00048 if (mVerbose)
00049 {
00050 putchar('-');
00051 fflush(stdout);
00052 }
00053 }
00054 }
00055
00056
00057 void *Watchdog::WatchdogThread(void*)
00058 {
00059 setuid(getuid());
00060
00061 if (mVerbose) puts("WatchdogThread: Started.");
00062
00063 while(1)
00064 {
00065 sleep(2*mQuantumTime);
00066
00067 if (mBeat == 1)
00068 {
00069 mBeat = 0;
00070 }
00071 else
00072 {
00073 puts("WatchdogThread: CPU exhaustion detected. Exiting.");
00074 exit(1);
00075 }
00076 }
00077 return 0;
00078 }
00079
00080
00081 bool Watchdog::Start(unsigned int quantum, bool verbose)
00082 {
00083 if (mStarted)
00084 return true;
00085
00086 if (quantum < 1)
00087 {
00088 puts("Watchdog::Start(): Time quantum must be at least 1 second.");
00089 return false;
00090 }
00091
00092 mVerbose = verbose;
00093
00094 pthread_t beat_thread;
00095 pthread_attr_t beat_attrs;
00096
00097 pthread_attr_init(&beat_attrs);
00098
00099 if (pthread_create(&beat_thread,
00100 &beat_attrs,
00101 &BeatThread, 0) != 0)
00102 {
00103 puts("Watchdog::Start(): Failed to create beat thread (you need to be root).");
00104 perror("pthread_create()");
00105 return false;
00106 }
00107
00108 pthread_t watchdog_thread;
00109 pthread_attr_t watchdog_attrs;
00110 struct sched_param watchdog_param;
00111
00112 watchdog_param.sched_priority = 99;
00113
00114 pthread_attr_init(&watchdog_attrs);
00115 pthread_attr_setschedpolicy(&watchdog_attrs,SCHED_FIFO);
00116 pthread_attr_setschedparam(&watchdog_attrs,&watchdog_param);
00117
00118 if (pthread_create(&watchdog_thread,
00119 &watchdog_attrs,
00120 &WatchdogThread, 0) != 0)
00121 {
00122 puts("Watchdog::Start(): Failed to create watchdog thread (you need to be root).");
00123 perror("pthread_create()");
00124 return false;
00125 }
00126
00127 mStarted = true;
00128
00129 return true;
00130 }
00131
00132 }
00133