What's the purpose of the timer? If the signal handler initiates a sequence where you are writing to anything used elsewhere, or reading data that the process might have been writing to at the time, I would think this is subject to the same caveats as threading, namely, that even with a single int, it is possible that you occasionally interrupt a write halfway through (meaning, reading from that int will produce a garbage value), in which case you would be better off actually using a thread and proper thread safe locks on the data.
Code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// compile C99 -lpthread
// for passing data to the timer
struct threadData {
pthread_mutex_t *lock;
int sleepTime;
int *data;
};
// timer function
void *timer (void *data) {
struct threadData *td = data;
sleep(td->sleepTime);
pthread_mutex_lock(td->lock);
// reset
*(td->data) = 0;
pthread_mutex_unlock(td->lock);
return NULL;
}
int main(void) {
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int x = 1;
struct threadData data = {
.lock = &lock,
.sleepTime = 3,
.data = &x
};
pthread_t id;
// create and detach the timer
pthread_create(&id, NULL, timer, (void*)&data);
pthread_detach(id);
// do stuff until the timer goes off
while (1) {
pthread_mutex_lock(&lock);
if (!x) break;
printf("%d\n", x++);
pthread_mutex_unlock(&lock);
}
printf("done\n");
pthread_mutex_destroy(&lock);
return 0;
}