33#include "printer.h"
44#include "reader.h"
55
6+
67int g_nproc = 0 ;
78static struct proc_stat * g_dataBuffer [BUFFER_SIZE ];
89pthread_mutex_t g_dataBufferMutex = PTHREAD_MUTEX_INITIALIZER ;
@@ -18,7 +19,12 @@ static pthread_t readerThreadId;
1819static pthread_t analyzerThreadId ;
1920static pthread_t printerThreadId ;
2021
21- void handler (int signum ) {
22+
23+ static int working [THREADS ];
24+ static pthread_mutex_t watchdogMutex = PTHREAD_MUTEX_INITIALIZER ;
25+
26+ static void handler (int signum ) {
27+ (void )signum ;
2228 pthread_cancel (readerThreadId );
2329 pthread_cancel (printerThreadId );
2430 pthread_cancel (analyzerThreadId );
@@ -48,7 +54,34 @@ unsigned long *get_item_from_print_buffer(void) {
4854 return g_printBuffer [index ];
4955}
5056
57+ void notify_watchdog (int id ){
58+ pthread_mutex_lock (& watchdogMutex );
59+ working [id ] = 1 ;
60+ pthread_mutex_unlock (& watchdogMutex );
61+ }
62+
63+ static void watchdog (void ) {
64+ while (1 ) {
65+ sleep (TIMEOUT );
66+ pthread_mutex_lock (& watchdogMutex );
67+ for (int i = 0 ; i < THREADS ; i ++ ) {
68+ if (working [i ] == 0 ) {
69+ pthread_mutex_unlock (& watchdogMutex );
70+ perror ("Error: Thread not responding... Terminating\n" );
71+ handler (-1 );
72+ return ;
73+ }
74+ working [i ] = 0 ;
75+ }
76+ pthread_mutex_unlock (& watchdogMutex );
77+ }
78+ }
79+
80+
5181int main (void ) {
82+ struct sigaction action ;
83+ memset (& action , 0 , sizeof (struct sigaction ));
84+
5285 if (get_nproc (& g_nproc ) == -1 ) {
5386 exit (EXIT_FAILURE );
5487 }
@@ -76,11 +109,11 @@ int main(void) {
76109 pthread_create (& analyzerThreadId , NULL , analyzer , NULL );
77110 pthread_create (& printerThreadId , NULL , printer , NULL );
78111
79- struct sigaction action ;
80- memset (& action , 0 , sizeof (struct sigaction ));
81112 action .sa_handler = handler ;
82113 sigaction (SIGTERM , & action , NULL );
83114
115+ watchdog ();
116+
84117 pthread_join (readerThreadId , NULL );
85118 pthread_join (analyzerThreadId , NULL );
86119 pthread_join (printerThreadId , NULL );
@@ -92,6 +125,8 @@ int main(void) {
92125 pthread_mutex_destroy (& g_printBufferMutex );
93126 sem_destroy (& g_printFilledSpaceSemaphore );
94127 sem_destroy (& g_printLeftSpaceSemaphore );
128+
129+ pthread_mutex_destroy (& watchdogMutex );
95130 for (int i = 0 ; i < BUFFER_SIZE ; i ++ ) {
96131 free (g_dataBuffer [i ]);
97132 free (g_printBuffer [i ]);
0 commit comments