Timer implementation for Linux Users

Source: Internet
Author: User

Note: The original header file is missing and can be added later.

There are two types of timers in Linux:

1. Alarm

Alarm () and signal () are enough if they are not required to be accurate.

Unsigned int alarm (unsigned int seconds)

Function Description: Alarm () is used to set the signal sigalrm to be transmitted to the current process after the number of seconds specified by the seconds parameter. If the seconds parameter is 0, the previously set alarm is canceled and the remaining time is returned.

Return Value: returns the remaining seconds of the previous alarm. If no alarm is set, 0 is returned.

After alarm () is executed, the process continues to be executed. In the later stage (after alarm), the process will receive the signal sigalrm and execute its processing function in seconds.

#include #include #include void sigalrm_fn(int sig){printf("alarm!\n");alarm(2);return;}int main(void){signal(SIGALRM, sigalrm_fn);alarm(1);while(1) pause();}

2. setitimer ()

Int setitimer (INT which, const struct itimerval * value, struct itimerval * ovalue ));

Setitimer () is more powerful than alarm and supports three types of Timers:

Itimer_real: calculated based on the real time of the system. It sends the sigalrm signal.

Itimer_virtual:-calculate the time spent by the process in the user State, and it sends the sigvtalrm signal.

Itimer_prof: calculates the time spent by the process in the user and kernel modes, and sends the sigprof signal.

Setitimer () the first parameter which specifies the timer type (one of the above three); the second parameter is an instance of the structure itimerval; the third parameter can not be processed.

If setitimer () is called successfully, 0 is returned; otherwise,-1 is returned.

The following is a simple example of setitimer calling. In this example, a sigalrm is sent every second and a sigvtalrm signal is sent every 0.5 seconds:

#include #include #include #include #include #include int sec;void sigroutine(int signo){switch (signo){case SIGALRM:printf("Catch a signal -- SIGALRM \n");signal(SIGALRM, sigroutine);break;case SIGVTALRM:printf("Catch a signal -- SIGVTALRM \n");signal(SIGVTALRM, sigroutine);break;}return;}int main(){struct itimerval value, ovalue, value2; //(1)sec = 5;printf("process id is %d\n", getpid());signal(SIGALRM, sigroutine);signal(SIGVTALRM, sigroutine);value.it_value.tv_sec = 1;value.it_value.tv_usec = 0;value.it_interval.tv_sec = 1;value.it_interval.tv_usec = 0;setitimer(ITIMER_REAL, &value, &ovalue); //(2)value2.it_value.tv_sec = 0;value2.it_value.tv_usec = 500000;value2.it_interval.tv_sec = 0;value2.it_interval.tv_usec = 500000;setitimer(ITIMER_VIRTUAL, &value2, &ovalue);for(;;);}

(1) struct itimerval

struct itimerval {struct timeval it_interval; /* timer interval */struct timeval it_value; /* current value */};itimerval: i --> intervalval --> value

It_value in the itimerval structure is the time for reduction. When this value is 0, a corresponding signal is sent. Then, it_value is set to it_interval.

(2) setitimer ()

Setitimer () sets a timer for the process in which it is located, if itimerval. if the value of it_interval is not 0 (neither of the two it_interval fields is 0), the timer will remain valid (a signal will be sent every time)

Note: The Linux signal mechanism is basically inherited from UNIX systems. In early Unix systems, the signal mechanism was relatively simple and original, and some problems were exposed in practice. Therefore, the signals built on the early mechanism were called "unreliable signals ", signals smaller than sigrtmin (sigrtmin = 32, sigrtmax = 63) are unreliable signals. This is the source of "unreliable signal. The main problem is that each time a process processes a signal, it sets the response to the signal as the default action. In some cases, it may lead to incorrect signal processing. Therefore, if you do not want such an operation, you need to call signal () again at the end of the signal processing function (), reinstall the signal.

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Setitimer () is a Linux API, not the standard library of C language. setitimer () has two functions. One is to execute a function after a specified period of time, the second is to execute a function in each cell for a period of time. The following program demo uses setitimer ().

View plaincopy to clipboardprint?
  1. /*
  2. Filename: timer. cpp
  3. Compiler: GCC 4.1.0 on Fedora Core 5
  4. Description: setitimer () set the interval to run Function
  5. Synopsis: # include <sys/time. h>
  6. Int setitimer (INT which, const struct itimerval * value, struct itimerval * ovalue );
  7. Struct itimerval {
  8. Struct timerval it_interval;
  9. Struct timerval it_value;
  10. };
  11. Struct timeval {
  12. Long TV _sec;
  13. Long TV _usec;
  14. }
  15. Release: 11/25/2006
  16. */
  17. # Include <stdio. h> // for printf ()
  18. # Include <unistd. h> // For pause ()
  19. # Include <signal. h> // for signal ()
  20. # Include <string. h> // For memset ()
  21. # Include <sys/time. h> // struct itimeral. setitimer ()
  22. Void printmsg (INT );
  23. Int main (){
  24. // Get System Call result to determine successful or failed
  25. Int res = 0;
  26. // Register printmsg to sigalrm
  27. Signal (sigalrm, printmsg );
  28. Struct itimerval tick;
  29. // Initialize struct
  30. Memset (& tick, 0, sizeof (tick ));
  31. // Timeout to run function first time
  32. Tick. it_value. TV _sec = 1; // Sec
  33. Tick. it_value. TV _usec = 0; // micro sec.
  34. // Interval time to run Function
  35. Tick. it_interval. TV _sec = 1;
  36. Tick. it_interval. TV _usec = 0;
  37. // Set timer, itimer_real: Real-Time to decrease timer,
  38. // Send sigalrm when timeout
  39. Res = setitimer (itimer_real, & tick, null );
  40. If (RES ){
  41. Printf ("set timer failed !! \ N ");
  42. }
  43. // Always sleep to catch sigalrm Signal
  44. While (1 ){
  45. Pause ();
  46. }
  47. Return 0;
  48. }
  49. Void printmsg (INT num ){
  50. Printf ("% s", "Hello world !! \ N ");
  51. }
/* Filename    : timer.cppCompiler    : gcc 4.1.0 on Fedora Core 5Description : setitimer() set the interval to run functionSynopsis    : #include <sys/time.h>              int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue);              struct itimerval {                struct timerval it_interval;                struct timerval it_value;              };               struct timeval {                long tv_sec;                long tv_usec;              }            Release     : 11/25/2006*/#include <stdio.h>    // for printf()#include <unistd.h>   // for pause()#include <signal.h>   // for signal()#include <string.h>   // for memset()#include <sys/time.h> // struct itimeral. setitimer()void printMsg(int);int main() {  // Get system call result to determine successful or failed  int res = 0;  // Register printMsg to SIGALRM  signal(SIGALRM, printMsg);    struct itimerval tick;  // Initialize struct  memset(&tick, 0, sizeof(tick));  // Timeout to run function first time  tick.it_value.tv_sec = 1;  // sec  tick.it_value.tv_usec = 0; // micro sec.  // Interval time to run function  tick.it_interval.tv_sec = 1;  tick.it_interval.tv_usec = 0;  // Set timer, ITIMER_REAL : real-time to decrease timer,  //                          send SIGALRM when timeout  res = setitimer(ITIMER_REAL, &tick, NULL);  if (res) {    printf("Set timer failed!!\n");  }  // Always sleep to catch SIGALRM signal  while(1) {    pause();  }  return 0;  }void printMsg(int num) {  printf("%s","Hello World!!\n");}

When the time for setitimer () to be executed is reached, sigalrm signal is called. Therefore, in line 30th, the function to be executed by signal () is specified to sigalrm. Set the timer in the second line of the call setitimer (), but the second parameter of setitimer () is sturct, which is used to set the timeout time. Therefore, the struct is set for the second line to the second line. Itimerval. it_value sets the number of seconds after the first function execution. itimerval. it_interval sets the number of seconds after the function execution. If you only want to delay the function execution for a period of time, you only need to set
Itimerval. it_value. If you want to set the inter-lattice to execute the function for a period of time, it_value and it_interval must be set. Otherwise, the first time the funtion cannot be executed, let alone the subsequent interval execution. The TV _sec values for rows 36th and 39th are sec, 37th and 40 Act micro Sec (0.001 sec ). Itimer_real, the first parameter of row 43rd, indicates that timer is reduced in real-time mode, and sigalrm signal is sent out in timeout. The third parameter stores the old timeout value. If this parameter is not required, specify NULL.
The command system enters the sleep state for pause () of Line 1. Wait for any signal and use the while (1) infinite loop to execute pause (), in this way, you can always receive sigalrm signal to execute the function at intervals. If while (1) is removed, the function will only be executed once.

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------

In Linux, there is also a high-precision timer, namely posix_timer. I remember that when I was reading the code, the clock_realtime timer seemed to use the rdtsc command, but now I'm not sure about it. In principle, you can also use the rdtsc command during frequency conversion, because we also know the CPU frequency, and the kernel is also known during frequency conversion.

The following is an example of my timer_create. The Rt library must be added during compilation. This is the Linux realtime Library:

Gcc-O test. c

# Include <stdio. h>
# Include <unistd. h>
# Include <signal. h>
# Include <stdlib. h>
# Include <time. h>

# Define rdtsc (low, high) _ ASM _ volatile _ ("rdtsc": "= A" (low), "= D" (high ))

Timer_t tt;

Void handler (INT Sig, siginfo_t * extra, void * Cruft)
{
Static last_ I = 0;
Unsigned int I, J;
Rdtsc (I, j );
Printf ("Time: % u, % u, [% u] % Uhz", J, I, i-last_ I, (i-last_ I) * 10/1000000 );
Last_ I = I;
}

Int main ()
{
Int I = 0;
Sigset_t sigset;

Sigfillset (& sigset );
Sigdelset (& sigset, sigrtmin );
Sigprocmask (sig_setmask, & sigset, null );

Struct sigaction SA;
Sigfillset (& SA. sa_mask );
SA. sa_flags = sa_siginfo;
SA. sa_sigaction = handler;

If (sigaction (sigrtmin, & SA, null) <0)
{
Perror ("sigaction failed ");
Exit (-1 );
}

Struct sigevent timer_event;
Struct itimerspec timer;

Timer. it_interval. TV _sec = 0;
Timer. it_interval. TV _nsec = 100*1000*1000;
Timer. it_value = timer. it_interval;

Timer_event.sigev_notify = sigev_signal;
Timer_event.sigev_signo = sigrtmin;
Timer_event.sigev_value.sival_ptr = (void *) & tt;

If (timer_create (clock_realtime, & timer_event, & TT) <0)
{
Perror ("timer_create failed ");
Exit (-1 );
}

If (timer_settime (TT, 0, & timer, null) <0)
{
Perror ("timer_settime failed ");
Exit (-1 );
}

While (I ++ <10)
{
Pause ();
}

Return 0;
}

Output result:

Time: 166081,193 4350847, [1934350847] 2163Hz
Time: 166081,212 0528291, [186177444] 1861Hz
Time: 166081,230 6679576, [186151285] 1861Hz
Time: 166081,249 4695630, [188016054] 1880Hz
Time: 166081,268 0865389, [186169759] 1861Hz
Time: 166081,286 7018473, [186153084] 1861Hz
Time: 166081,305 3152230, [186133757] 1861Hz
Time: 166081,323 9309935, [186157705] 1861Hz
Time: 166081,342 5467261, [186157326] 1861Hz
Time: 166081,361 1639266, [186172005] 1861Hz

Http://blog.chinaunix.net/uid-23215128-id-2521378.html

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.