I wrote the following code to implement a periodic thread terminated when someone presses escape. The result is a periodic thread that continues also after i pressed escape. Can you tell me where is the error please? The compiler compiles without any error and warning. Before reading the code jump to EDIT below.
#include <stdio.h>
#include <pthread.h>
#include <allegro.h>
#include <time.h>
void *task(void *p);
void time_add_ms(struct timespec *t, int ms);
int main()
{
int tret;
int a = 1;
allegro_init();
install_keyboard();
tret = pthread_create(&tid, NULL, task, (void*)&a);
pthread_join(tid, NULL);
printf("Thread1 returns %d\n", tret);
allegro_exit();
return 0;
}
/* Sommare quantità temporale espressa in ms al tempo nella struttura timespec */
void time_add_ms(struct timespec *t, int ms)
{
t->tv_sec += ms / 1000;
t->tv_nsec += (ms % 1000) * 1000000;
if (t->tv_nsec > 1000000000){
t->tv_nsec -= 1000000000;
t->tv_sec += 1;
}
}
/* Funzione da trasformare in task */
void *task(void *p)
{
struct timespec t;
int period = 100;
int *pi;
char scan = 0;
clock_gettime(CLOCK_MONOTONIC, &t);
time_add_ms(&t, period);
pi = (int *)p;
while (scan != KEY_ESC) {
if (keypressed()) scan = readkey() >> 8;
printf("This is TASK %d\n", *pi);
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);
time_add_ms(&t, period);
}
}
EDIT: maybe i found the problem, when i press escape, it prints the symbol ^, so the compiler or allegro doen't recognize the esc key.