I wrote a timer following some examples from the web:
void fun(int i)
{
struct itimerval to;
//do something
signal(SIGALRM, fun);
to.it_interval.tv_sec = 0;
to.it_interval.tv_usec = 0;
to.it_value.tv_sec = 60;
to.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &to, 0);
}
in the main function, I just call this fun once and then do a while loop there.
The program behave well except that it exhaust the cpu fully (by 99% or 100%), but if I remove the while loop, the “fun” function is called just once. How could I keep it being called periodically while avoid occupy the cpu for 100%?
You probably want to use an event loop, so that your program sleeps and consumes no CPU when there is nothing to do. An easy way would be to use libevent.
Otherwise, use
select()orpselect().