Look at a piece of code first
#include <stdio.h> #include <time.h> #include <sys/time.h> #include <stdlib.h> #include < signal.h>static int count = 0;void Set_timer () {struct Itimerval itv;itv.it_value.tv_sec = 3; Timer start after 3 seconds lateritv.it_value.tv_usec = 0;itv.it_interval.tv_sec = 1;itv.it_interval.tv_usec = 0;setiti Mer (Itimer_real,&itv,null);} void Signal_handler (int m) {count + +;p rintf ("%d\n", count);} int main () {signal (Sigalrm,signal_handler); Set_timer (); while (count <); exit (0); return 0;}
This code implements the function: 3 seconds after the timer is started, and then every 1 seconds to the terminal to print the increment value of count, when count to 10 o'clock program exits.
Structure prototype:
struct Itimerval { struct timeval it_interval;/* Next value */ struct timeval it_value; /* Current value */ };
struct Timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ };
That
struct Itimerval { struct timeval it_interval;/* Timer Reset Intermittent value */ struct timeval it_value; /* Initial value starting first after the timer is installed */};struct timeval { long tv_sec; /* sec */ long tv_usec; /* Subtle (1/1000000) */};
then look at this function:
int Setitimer (int which, const struct Itimerval *value,struct itimerval *ovalue);
Setitimer () sets the struct that value points to the current value of the timer, and returns the original value of the timer if Ovalue is not null.
Which: Intermittent timer type with three options
The Itimer_real//value is 0, the value of the timer decreases in real time, and the signal sent is SIGALRM.
Itimer_virtual//value is 1, Process execution decrements the timer value, the signal sent is SIGVTALRM.
The Itimer_prof//numeric value is 2, and the process and system execution decrements the timer value, and the signal sent is sigprof.
Return Description:
When executed successfully, returns 0. The failed return -1,errno is set to one of the following values
Efault:value or ovalue is not a valid pointer
EINVAL: Its value is not one of itimer_real,itimer_virtual or itimer_prof