How to Use setitimer in linux c Programming, linuxsetitimer
In linux c programming. Setitimer is a function that is frequently used than timer. Latency and timing
Header files to be introduced during use:
#include
Setitimer function prototype:
int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);
The which limit number indicates the type. Optional values:
ITIMER_REAL: calculated based on the real time of the system. It sends the SIGALRM signal.
ITIMER_VIRTUAL: calculates the time spent by the process in the user State. It sends the SIGVTALRM signal.
ITIMER_PROF: the time spent by the process in the user and kernel modes. It sends a SIGPROF signal.
The new_value and old_value are the itimerval struct. Let's take a look at the definition of the itimerval struct:
struct itimerval { struct timeval it_interval; /* next value */ struct timeval it_value; /* current value */};struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */};
Itimeval is composed of two timeval struct, including TV _sec and TV _usec. The value of TV _se is second. TV _usec is in microseconds (that is, 1/1000000 seconds)
The settimer mechanism is to first Countdown to it_value and trigger a signal when it_value is zero. Then reset to it_interval. Continue to countdown to it_value. Keep repeating like this.
Based on this mechanism. Setitimer can be used for both delayed and scheduled operation.
If it_value is 0, the signal will not be triggered, so the it_value must be greater than 0. If it_interval is zero, only the delay will occur. Not scheduled (that is, only one signal is triggered ).
Old_value limit, which is frequently unavailable. Set to NULL, which is used to store the new_value value set during the last setitimer call.
Example:
#include
#include
#include
void signalHandler(int signo){ switch (signo){ case SIGALRM: printf("Caught the SIGALRM signal!\n"); break; }}int main(int argc, char *argv[]){ signal(SIGALRM, signalHandler); struct itimerval new_value, old_value; new_value.it_value.tv_sec = 0; new_value.it_value.tv_usec = 1; new_value.it_interval.tv_sec = 0; new_value.it_interval.tv_usec = 200000; setitimer(ITIMER_REAL, &new_value, &old_value); for(;;); return 0;}