2

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%?

realjin
  • 1,485
  • 1
  • 19
  • 38

3 Answers3

4

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() or pselect().

Community
  • 1
  • 1
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
1

you can use pause(). link

in the main :

fun(i);
while(1)
    pause(); 

and fun() will execute fun every 60 seconds.

sleep() or Sleep() (windows) is also your friend. (in the loop instead of pause())

another way is to use sigsuspend() link

Hicham
  • 983
  • 6
  • 17
0

select() in C would do what you want. And it is of microsecond granularity.

varunl
  • 19,499
  • 5
  • 29
  • 47