Clock programming under Linux

Source: Internet
Author: User
Tags sleep function


1. Clock-related API function prototypes

#include  <unistd.h>unsigned int sleep (unsigned int seconds); unsigned int  alarm (unsigned int seconds); Int usleep (useconds_t usec); #include  <sys/time.h >int getitimer (Int which, struct itimerval *curr_value); Int setitimer (int  which, const struct itimerval *new_value,                      struct itimerval  *old_value);            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 */           };

Implementation of the 2.sleep

sleep In fact, everyone should be unfamiliar, many languages have the corresponding implementation, its role is to set a delay, wait for delay, suspend process. The wait time arrives and the recovery process runs. The implementation of sleep in Linux is implemented using alarm, the API function. The implementation steps are as follows:

One: Set a processing function for SIGALRM (SIGALRM is a clock signal, time to the kernel will send SIGALRM signal to the process)

Two:. Call alarm (num_seconds); Set timer

Three: Call pause to suspend the process.

This is the process of a sleep function, the code is as follows:

#include <stdio.h> #include <stdlib.h> #include <signal.h>void wakeup (int); void do_ Thing ();int main  ( int argc, char *argv[] ) {         printf ("about to sleep for seconds\n");         signal (Sigalrm,wakeup);         alarm (4);         pause ();         printf ("Morning  so son?\n ");         return exit_success;}         /* ----------  end of function  main  ---------- */void wakeup (int signum) {                 printf ("alarm received from kernel\n");}

Alarm is a Linux timer, its first purpose is to use as a delay, another use is to dispatch a future do something else at the same time.

Set the timer through alarm, and then continue doing something else, when the timer reaches 0, the signal is sent, and the handler function is called.

#include <stdio.h> #include <stdlib.h> #include <signal.h>void do_thing () int main   ( int argc, char *argv[] ) {         printf ("about to sleep for seconds\n");         Signal (sigalrm,do_thing);         alarm (4);         while (1) {                 sleep (2);                 printf ("Continue \ n");        }         return exit_success;}         /* ----------  end of function  main  ---------- */void do_thing () {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; printf ("\ n" executed after 4 seconds);} 

Sleep,alarm can only handle second-level delays and timers. Ulseep function provided in Linux provides a higher precision latency


3. Three timers for a process

Each process has three timers, namely:

Itimer_real used in real time. If the watch records the same. When this timer is exhausted, a SIGLRM message is sent

Itimer_virtual This timer is only timed when the user is running in the user state

Itimer_prof This timer is used when the process runs in a user state or is called by the process and is stuck in a nuclear mindset.

Three timers, does the computer have three clocks? In fact, the computer has only one clock. The way it works is that each process has its own counter, and the CPU iterates through all the processes every other time to decrement the timer for each process.


4. Interval Timer programming

The interval timer differs from the normal timer, which has two values, one is the initial time interval and the other is the repeating interval setting. The following is an example of an interval timer:

#include <stdio.h> #include <sys/time.h> #include <signal.h> #include <stdlib.h>void  Countdown (int); int set_ticker (int);int main  ( int argc, char *argv[] ) {        //set signal processing function          Signal (sigalrm,countdown);         //Set Timer          if (Set_ticker ()  == -1)                  perror ("Set_ticker:");         else           //process continues to run                  while (1)                  done_other_thing ();         return exit_success;}         /* ----------  end of function  main  ---------- */void done_other_thing () {         sleep (1);         printf ("*****\n");} void countdown  (int signum) {        static int  num=10;        printf ("%d..", num--);         fflush (stdout);         if (num<0) {                 printf ("DONE! \ n ");                 exit (0);         }}        /* ---- -  end of function countdown  ----- */int set_ticker (int n_msecs) {         struct itimerval new_timeset;         long n_sec,n_usecs;        n_sec = n_msecs /  1000;        n_usecs =  (n_msecs % 1000)  *1000L;        new_timeset.it_interval.tv_sec = n_sec;         new_timeset.it_interval.tv_usec = n_usecs;         new_timeset.it_value.tv_sec = n_sec;         new_timeset.it_value.tv_usec = n_usecs;         return setitimer (itimer_real,&new_timeset,null);}

The above operation is as follows: first set the signal processing function countdown, and then set the timer, the initial value is 500 milliseconds is 500 milliseconds after the timer time, repeat interval is 500. After the initial 500 milliseconds arrives, the timer is reset to 500 milliseconds. After setting the timer, the program continues to run down for another time. 500 milliseconds to go. The countdown function. This function prints a number and decrements the value of the static variable num, and the value of NUM is less than 0 after repeated execution 10 times. And then start countdown again when you quit the whole program.

This article is from the "Focus on Linux" blog, so be sure to keep this source http://forlinux.blog.51cto.com/8001278/1532519

Related Article

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.