In some programs, we need to execute a function every once in a while. For example, each 2s,5s,10s performs a separate function. If have more than one timer, realize this function is very simple, need to separate timed 2s,5s,10s can. But only one timer in a single process is allowed in Linux. Can be implemented in the following ways.
First use the Setitimer function to register a 1s timer one_timer, because 1s can be the unit time that is divisible by 2s,5s,10s. Setitimer time arrival will produce SGIALRM signal, set the SGIALRM processing function for Multi_timer_manage, timed time will be executed multi_timer_manage function.
Defines a timers structure body that stores two variables. One is a timed time, the value is the desired time divided by the unit time, and the other is a function that is executed at timed times. Create timers Structures Two_timer, Five_timer, Ten_timer, and fill in timed times and functions that need to be performed.
Multi_timer_manage for the realization of a number of timer functions of the core, in the multi_timer_manage will be One_timer, Two_timer, ten_timer corresponding timing time minus one, if zero, then perform the corresponding function, and reset the timed time to the initial value and start the timer again. In this way, the function of multiple timers is implemented, the detailed code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#include <sys/time.h>
#include <signal.h>
struct Itimerval one_timer;
struct timers
{
int interval; Timed time
void (*handler) (); handler function
};
struct Timers Two_timer;
struct Timers Five_timer;
struct Timers Ten_timer;
void Multi_timer_manage ()
{
printf ("\ n---");
two_timer.interval--;
if (two_timer.interval==0)
{
two_timer.interval=2;
Two_timer.handler ();
}
five_timer.interval--;
if (five_timer.interval==0)
{
five_timer.interval=5;
Five_timer.handler ();
}
ten_timer.interval--;
if (ten_timer.interval==0)
{
ten_timer.interval=10;
Ten_timer.handler ();
}
}
void Two_output ()
{
printf ("2");
}
void Five_output ()
{
printf ("5");
}
void Ten_output ()
{
printf ("10");
}
void Init ()
{
One_timer.it_interval.tv_sec=1; Set the unit timer timed time
One_timer.it_value.tv_sec=1; Set the unit Timer initial value
Setitimer (Itimer_real,&one_timer,null); Initialize Unit timer
Signal (sigalrm,multi_timer_manage); A function that specifies that the unit timer is to be executed at timed time
two_timer.interval=2;
Two_timer.handler=two_output;
five_timer.interval=5;
Five_timer.handler=five_output;
ten_timer.interval=10;
Ten_timer.handler=ten_output;
}
int main ()
{
Init ();
while (1);
}
The results of the implementation are as follows:
---
---2
---
---2
---5
---2
---
---2
---
---2 5 10
---
---2
---
---2
---5
---2
---
---2
---
---2 5 10
......
Visible, every second output---, every 2 seconds Output 2, every 5 seconds output 5, every 10 seconds output 10.