C Implementation of several timers

Source: Internet
Author: User

1.linux Downgrade system function alarm (), Setitimer (), Sleep (), Usleep () (for subtle timing),

2. Simple C language Implementation gettimeofday () (subtle timing), time (),

3.windows available sleep () for microsecond timing

1.alarm ()

#include <unistd.h>
unsigned int alarm (unsigned int seconds);

function return value

Success: If the process has set an alarm time before calling this alarm (), the time remaining for the previous alarm time is returned, otherwise 0 is returned. No blocking!!!

Error:-1

Function: Call the alarm function to set an alarm, which is to tell the kernel to send SIGALRM signal to the current process after seconds seconds, the default processing action is to terminate the current process. Alarm Clock return

The return value is 0 or the number of seconds remaining for the previously set alarm time. If the seconds value is 0, which means that the previously set alarm is canceled, the return value of the function is still
Is the number of seconds left before the alarm time is set.
Cases

------Alarm
#include <unistd.h>
#include <stdio.h>
int main (void)
{
int counter;
Alarm (1);
for (counter=0; 1; counter++)
printf ("counter=%d", counter);
return 0;
}
The function of this program is to keep counting in 1 seconds, and 1 seconds to be SIGALRM signal end.
Check.

-----------"1.1 with the pause function to implement the sleep function!

#include <unistd.h>
int pause (void);
The pause function suspends the calling process until a signal is reached. If the signal processing action is to terminate the process, then the process terminates, the pause function has no chance to return, if the signal processing action is ignored, then
The process continues in a pending state, pause does not return, or if the signal processing action is capture, then pause returns -1,errno set to EINTR after the signal processing function is called, so pause has only an error
return value (think about what function you learned before that only the error return value?). The error code EINTR indicates "interrupted by signal."
Here we use alarm and pause to implement the sleep (3) function, called Mysleep.
Mysleep
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
void sig_alrm (int signo)
{
/* Nothing to do */
}
unsigned int mysleep (unsigned int nsecs)
{

struct sigaction newact, oldact;
unsigned int unslept;
Newact.sa_handler = SIG_ALRM;
Sigemptyset (&newact.sa_mask);
newact.sa_flags = 0;
Sigaction (SIGALRM, &newact, &oldact);
Alarm (NSECS);
Pause ();
unslept = alarm (0);
Sigaction (SIGALRM, &oldact, NULL);
return unslept;
}
int main (void)
{
while (1) {
Mysleep (2);
printf ("Seconds passed\n");
}
return 0;
}
1. The main function calls the Mysleep function, which calls Sigaction to register the handler function SIG_ALRM for the SIGALRM signal.
2. Call Alarm (NSECS) to set the alarm.
3. Call pause to wait for the kernel to switch to another process to run.
4. After nsecs seconds, the alarm expires and the kernel sends SIGALRM to the process.
5. Processing the pending signal from the kernel state before returning the user state of the process, and discovering the SIGALRM signal, whose processing function is SIG_ALRM.
6. Switch to the user state execution Sig_alrm function, enter the SIG_ALRM function SIGALRM signal is automatically shielded, from the SIG_ALRM function return SIGALRM signal automatically unblock. And then
The automatic system call Sigreturn enters the kernel again and returns to the main control flow (the Mysleep function called by the main function) of the user state to continue executing the process.
7. The pause function returns-1 and then calls Alarm (0) to cancel the alarm, calling Sigaction to restore the previous processing action of the SIGALRM signal.

2.setitimer ()------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------

Commonly used functions:
#include  <sys/time.h>
int getitimer  (int which, struct  Itimerval* value);
int setitimer  (int which, struct itimerval* newvalue, struct  Itimerval* oldvalue);

There are three states of which:
Itimer_real: For a specified time value, by natural time count, time to emit SIGALRM signal.
Itimer_virtual: For a specified time value, when only the user state (Process execution) counts, time to emit SIGVTALRM signal.
Itimer_prof: For a specified time value, the user state or kernel state (Process execution and system for process scheduling) are counted, time to, emit sigprof signal, and Itimer_virtval Union, commonly used to calculate the system kernel time and user time.

struct Timeval
{
Long tv_sec;/* sec */
Long tv_usec;/* microseconds */
};

struct Itimerval
{
struct Timeval it_interval; /* time interval *///cycle timing time
struct Timeval it_value;/* Current time count */First time elapsed
};
It_interval is used to specify how often the task is performed, and how long It_value is used to save the current time from the execution of the task. For example, you specify a it_interval of 2 seconds (microseconds is 0), the beginning of the time we put It_value is also set to 2 seconds (microseconds 0), when a second, It_value reduced to 1, and then 1 seconds, then it_value reduced 1, into 0, This time signal (tell the user time, can perform the task), and the system automatically resets the It_value reset to the value of It_interval, that is, 2 seconds, and then re-count.

-------------------------------Code Implementation

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>

static char msg[] = "Time is running out.\n";
static int len;


/* time ' s up */
void Prompt_info (int signo)
{
Write (Stderr_fileno, MSG, Len);
}

void Init_sigaction (void)
{
struct sigaction tact;

Tact.sa_handler = Prompt_info;
tact.sa_flags = 0;

Sigemptyset (&tact.sa_mask);
Sigaction (SIGALRM, &tact, NULL);
}

void Init_time ()
{
struct Itimerval value;

Value.it_value.tv_sec = 2;
value.it_value.tv_usec = 0;

Value.it_interval = Value.it_value;

/* Set Itimer_real */
Setitimer (Itimer_real, &value, NULL);
}

int main (int argc, char** argv)
{
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 the signal, the call signal handler Prompt_info outputs the string "Time is running" on the standard error.
For the use of itimer_virtual and itimer_prof similar, when you set the Setitimer inside the timer for the itimer_virtual, you put sigaction inside SIGALRM change 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 to output one, it is because the CPU between the user and the kernel switch is also a waste of time, This period of time is not counted within the specified time frame.

3.time () or Gettimeofday () Use time difference to calculate----------------------------------------------------------------------------------------------------------------- ---------

1. #include <signal.h>
2. #include <unistd.h>
3. #include <string.h>
4. #include <stdio.h>
5. #include <time.h>//include time () function

6. #include <sys/time.h>//contains the Gettimeofday () function

7. Staticchar msg[] = "I received a msg.\n";

8. int Len;
9. Static time_t Lasttime;
void show_msg (int signo)
11. {
Write (Stderr_fileno, MSG, Len);
13.}
Intmain ()
15. {
Structsigaction Act;
Unionsigval TSval;
18.
Act.sa_handler = show_msg;
act.sa_flags = 0;
Sigemptyset (&act.sa_mask);
Sigaction (&act, NULL);
23.
Len = strlen (msg);
Time (&lasttime);
(1)
27. {
Time_tnowtime;
29./* Get current time */
Time (&nowtime);
31./* Compare with last time, if greater than or equal to 2 seconds, send signal immediately */
if (Nowtime-lasttime >= 2)
33. {
34./* Send a signal to the main process and actually signal yourself */
Sigqueue (Getpid (), tsval);
Lasttime = Nowtime;
37.}
38.}
Return0;
40.}

If you want to calculate the time difference more accurately, you can change the time function to Gettimeofday, which can be precise and subtle.
There are several timing methods described above are different, in the timing efficiency, method and time accuracy also vary, which method to use, depends on the needs of your program

4 Sleep Implementation Method---------------------------------------------------------------------------------------------------------------- ---------------------------------------------

Let's take a look at how to implement timed tasks with sleep and usleep.
Download: timer2.c
1. #include <signal.h>
2. #include <unistd.h>
3. #include <string.h>
4. #include <stdio.h>
5.
6. Staticchar msg[] = "I received a msg.\n";
7. int Len;
8. void show_msg (int signo)
9. {
Write (Stderr_fileno, MSG, Len);
11.}
Intmain ()
13. {
Structsigaction Act;
Unionsigval TSval;
16.
Act.sa_handler = show_msg;
act.sa_flags = 0;
Sigemptyset (&act.sa_mask);
Sigaction (&act, NULL);
21st.
Len = strlen (msg);
while (1)
24. {
Sleep (2); /* Sleep 2 seconds */
26./* Send a signal to the main process and actually signal yourself */
Sigqueue (Getpid (), tsval);
28.}
Return0;
30.}
See, this is much simpler than the above, and you use a stopwatch to measure, the time is very accurate, specify 2 seconds to the output of a string. So, if you only do the general timing, it's time to perform a task, this method is the simplest.

C Implementation of several timers

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.