How to implement LINUX timer __linux

Source: Internet
Author: User
Tags time interval usleep

The purpose of using a timer is to perform a task periodically, or to perform a task at a specified time. In order to achieve this goal, there are generally two common and more effective methods. One is to use the Linux internal three timers, the other is with sleep, usleep function let the process sleeps for a period of time, in fact, there is a way, it is to use Gettimeofday, difftime and so on their own to calculate the time interval, and then time to carry out a task, But this method is inefficient, so it is not commonly used.

First look at the 3 internal timers that the Linux operating system provides for each process.

Itimer_real: Give a specified time interval, reduce this count by the actual time, and emit a SIGALRM signal when the time interval is 0

Itimer_virtual: Given a time interval, the count is reduced when the process executes, and the SIGVTALRM signal is emitted when the time interval is 0

Itimer_prof: Given a time interval, when the process executes or the system is scheduled for the process, reduce the count, time, send out the sigprof signal, this and itimer_virtual Union, commonly used to calculate the system kernel time and user time.

The functions used are:

#include <sys/time.h> int getitimer (int which, struct itimerval *value);   int Setitimer (int which, struct itimerval*newvalue, struct itimerval*);   Strcut Timeval {long tv_sec;/* sec/long tv_usec;/* microsecond/}; struct Itimerval {struct timeval it_interval;/* time interval/struct timeval it_value;//Current time count/};

It_interval is used to specify how often the task is performed, and how long the it_value is used to save the current time from the task. For example, you specify it_interval to be 2 seconds (microsecond 0), at the beginning we set the It_value time to 2 seconds (microseconds 0), when one second, it_value reduce one to 1, then 1 seconds, then it_value reduced 1, into 0, This time the signal (tell the user time, can perform the task), and the system automatically resets the It_value time to the It_interval value, that is 2 seconds, and then count again.

To help you understand this problem, let's look at an example:

  

      #include <sys/time.h> #include <stdio.h> #include <unistd.h> #in   Clude <signal.h> #include <string.h> static char msg[] = "Time is running out/n";   static int len;   Output information to standard error, telling user time to void prompt_info (int signo) {write (Stderr_fileno, MSG, Len);   ///Establish a signal processing mechanism void init_sigaction (void) {struct sigaction tact;   /* Signal to the task to perform the processing function for prompt_info*/Tact.sa_handler = Prompt_info;   tact.sa_flags = 0;   /* Initialize the signal set */Sigemptyset (&tact.sa_mask);   /* Establish signal processing mechanism * * Sigaction (SIGALRM, &tact, NULL);   } void Init_time () {struct Itimerval value;   /* Set the time interval to perform the task is 2 seconds 0 microseconds * * * * value.it_value.tv_sec = 2;   value.it_value.tv_usec = 0;   /* Set the initial time count is also 2 seconds 0 microseconds */value.it_interval = Value.it_value;   /* Set timer itimer_real*/setitimer (itimer_real, &value, NULL);   int main () {len = strlen (msg);   Init_sigaction ();   Init_time ();   while (1);   Exit (0); }

The program's Itmer_real timer sends a SIGALRM signal every 2 seconds, and when the main function receives this signal, the calling signal processing function prompt_info The string to output the time is running on the standard error.

The use of itimer_virtual and itimer_prof is similar, when you set the timer in Setitimer for itimer_virtual, you change sigaction inside Sigalrm to Sigvtalarm, Similarly, itimer_prof corresponds to Sigprof.

However, you may notice that when you use Itimer_virtual and itimer_prof, you take a stopwatch, you will find that the program output string time interval will be more than 2 seconds, or even 5-6 seconds will output one, as for why, I think about the ^_^

#include <signal.h> #include <unistd.h> #include <string.h> #include <stdio.h> static char   Msg[] = "I received a msg./n";   int Len;   void show_msg (int signo) {write (Stderr_fileno, MSG, Len);   int main () {struct Sigaction act;   Union Sigval TSval;   Act.sa_handler = show_msg;   act.sa_flags = 0;   Sigemptyset (&act.sa_mask);   Sigaction (M, &act, NULL);   Len = strlen (msg);   while (1) {Morpheus (2);/* Sleep 2 sec * * * send a signal to the main process, in fact, you send yourself a signal * * * SIGQUEUE (Getpid (), tsval);   return 0; }

Let's take a look at how to implement a timed task with sleep and usleep.

See, this is much simpler than the above, and you use a stopwatch test, time is accurate, specify 2 seconds to give you output a string. So, if you only do regular timing and have time to perform a task, this is the easiest way to do it.

Let's take a look at the timing by calculating your own time difference:

#include <signal.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include &l   t;time.h> static char msg[] = "I received a msg./n";   int Len;   Static time_t Lasttime;   void show_msg (int signo) {write (Stderr_fileno, MSG, Len);   int main () {struct Sigaction act;   Union Sigval TSval;   Act.sa_handler = show_msg;   act.sa_flags = 0;   Sigemptyset (&act.sa_mask);   Sigaction (M, &act, NULL);   Len = strlen (msg);   Time (&lasttime);   while (1) {time_t nowtime;   /* Get Current time * * (&nowtime); /* Compared with the previous time, if greater than or equal to 2 seconds, then immediately send a signal/if (Nowtime-lasttime >= 2) {/* to the main process to send a signal, in fact, you send yourself a signal/Sigqueue (Getpid (), 50,   TSval);   Lasttime = Nowtime;   } return 0; }

This differs from the above in that it is the manual calculation of the time difference, if you want more accurate calculation time difference, you can change the time function to Gettimeofday, this can be accurate to subtle.

The above mentioned several timing methods are different, in the timing efficiency, method and time of the accuracy of the difference, the use of which method, depends on the needs of your program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.