First of all, consider using the sleep
function if possible. If you have to do actual work for a specified time period, which I find unlikely, the following ugly solution would work:
#include <signal.h>
int alarmed = 0;
void sigh(int signum) {
alarmed = 1;
}
int main(void){
/* ... */
signal(SIGALRM, &sigh);
alarm(5); // Alarm in 5 seconds
while(!alarmed) {
/* Do work */
}
/* ... */
}
A solution using time.h
would also be possible, and perhaps simpler and/or more accurate, depending on context:
#include <time.h>
int main(void){
/* ... */
clock_t start = clock();
while(clock() - start < 5 * CLOCKS_PER_SEC) {
/* Do work */
}
/* ... */
}