(24) Linux new timer: TIMEFD and related operation function

Source: Internet
Author: User
Tags readable set time

TIMERFD is a timer interface provided by Linux for the user program. This interface is based on file descriptors, and can be used for select/poll scenarios by using the file descriptor's readable event for timeout notification.

One, related operation function

#include <sys/timerfd.h>

int timerfd_create (int clockid, int flags);

int timerfd_settime (int FD, int flags, const struct ITIMERSPEC * new_value, struct itimerspec *old_value);

int timerfd_gettime (int fd, struct itimerspec *curr_value);

Two, timerfd_create

int timerfd_create (int clockid, int flags);

It is used to create a timer descriptor TIMERFD

First parameter: clockid specifies a time type with two values:

Clock_realtime:systemwide REALTIME clock. System-wide real-time clock

Clock_monotonic: Operates at a fixed rate, never adjusted and reset, and is unaffected by any system Time-of-day clock modifications

Second parameter: Flags can be either 0 or O_cloexec/o_nonblock.

return value: TIMERFD (file descriptor)

Three, Timerfd_settime

Before explaining the function, you should understand two related structures:

structTimespec {time_t tv_sec; /*Seconds*/               LongTv_nsec;/*nanoseconds*/           }; structItimerspec {structTimespec It_interval;/*Interval for periodic timer*/               structTimespec It_value;/*Initial Expiration*/           };

The second struct Itimerspec is timerfd to set the time-out structure of the body, its member It_value represents the timer first time out, It_interval indicates the time-out after the timeout is how often time-out

int timerfd_settime (int FD, int flags, const struct ITIMERSPEC * New_value , struct Itimerspec * Old_value );

Function: Used to start or close a timer specified by FD

Parameters:

FD:TIMERFD, there is a timerfd_create function to return

Fnew_value: Specify a new time-out, set the New_value.it_value nonzero to start the timer, otherwise turn off the timer, if the New_value.it_interval is 0, then the timer is only timed once, that is, the initial time, Otherwise, once every set time expires

Old_value: NOT NULL, returns the timeout before the timer is set this time

The flags:1 represents the absolute time, and the 0 represents the relative time.

Four, Timerfd_gettime

int timerfd_gettime (int fd, struct itimerspec *curr_value);

This function is used to obtain the time remaining for the timer from the next timeout. If the timer has expired at the time of the call and the timer is in loop mode (the struct itimerspec::it_interval is not 0 when the timeout is set), then the timer starts again after calling this function.

The it_value field returns the amount of time until the timer would next expire. If Both fields of this structure be zero, then the timer is currently disarmed. This field is always contains a relative value, regardless of whether the tfd_timer_abstime flag is specified when Setting the timer.

The it_interval Field returns the interval of the timer. If Both fields of this structure be zero, then the timer was set to expire just once, at the time specified by Curr_v Alue.it_value.

Five, read read TIMEFD timeout event notification

Read (2) If the timer has a already expired one or more times since it settings were last modified using timerfd_settime (), or since the last successful read (2), then the buffer given to read (2) returns an unsigned 8-byte integer (UI nt64_t) containing the number of expirations that has occurred. (The returned value is in host byte order, i.e., the native byte order for integers on the host machine.)

If No timer expirations has occurred at the time of the read (2), then the call either blocks until the next timer Expirat  Ion, or fails with the error eagain If the file descriptor have been made nonblocking (via the use of the FCNTL (2) F_SETFL operation to set theo_nonblock flag).

A Read (2) would fail with the error EINVAL If the size of the supplied buffer was less than 8 bytes.

When the timer expires, the read Read event occurs to be readable, returning the timeout number (from the Last Call to Timerfd_settime () Start or last read successful read start), which is a 8-byte unit64_t type integer, if the timer does not have a timeout event, Read will block if TIMERFD is blocking mode, otherwise eagain error (O_nonblock mode) is returned, and if read provides a buffer less than 8 bytes will be returned with a einval error.

Six, sample code

Example of the Man Handbook:

The following program creates a timer and then monitors its progress. The program accepts up to three command-line arguments. The first argument specifies the number of seconds for the initial expiration of the timer. The second argument specifies the interval for the timer, in seconds. The third argument specifies the number of times the program should allow the timer to expire before terminating. The second and third command-line arguments are optional.

#include <sys/timerfd.h>#include<time.h>#include<unistd.h>#include<stdlib.h>#include<stdio.h>#include<stdint.h>/*Definition of uint64_t*/#defineHandle_error (msg) do {perror (msg), exit (Exit_failure);} while (0)Static voidPrint_elapsed_time (void){   Static structTimespec start; structTimespec Curr; Static intFirst_call =1; intsecs, nsecs; if(first_call) {First_call=0; if(Clock_gettime (clock_monotonic, &start) = =-1) Handle_error ("Clock_gettime"); }   if(Clock_gettime (clock_monotonic, &curr) = =-1) Handle_error ("Clock_gettime"); secs= Curr.tv_sec-start.tv_sec; Nsecs= Curr.tv_nsec-start.tv_nsec; if(Nsecs <0) {secs--; Nsecs+=1000000000; } printf ("%d.%0 3d:", secs, (Nsecs +500000) /1000000);}intMain (intargcChar*argv[]) {   structItimerspec New_value; intMax_exp, FD; structTimespec now;   uint64_t exp, tot_exp;   ssize_t s; if((argc! =2) && (argc! =4) {fprintf (stderr,"%s init-secs [interval-secs max-exp]\n", argv[0]);   Exit (Exit_failure); }   if(Clock_gettime (clock_realtime, &now) = =-1) Handle_error ("Clock_gettime"); /*Create a clock_realtime absolute timer with initial expiration and interval as specified on command line*/new_value.it_value.tv_sec= Now.tv_sec + atoi (argv[1]); New_value.it_value.tv_nsec=now.tv_nsec; if(ARGC = =2) {new_value.it_interval.tv_sec=0; Max_exp=1; } Else{new_value.it_interval.tv_sec= Atoi (argv[2]); Max_exp= Atoi (argv[3]); } new_value.it_interval.tv_nsec=0; FD= Timerfd_create (Clock_realtime,0); if(FD = =-1) Handle_error ("timerfd_create"); if(Timerfd_settime (FD, Tfd_timer_abstime, &new_value, NULL) = =-1) Handle_error ("Timerfd_settime");   Print_elapsed_time (); printf ("Timer started\n");  for(Tot_exp =0; Tot_exp <max_exp;) {s= Read (FD, &AMP;EXP,sizeof(uint64_t)); if(s! =sizeof(uint64_t)) Handle_error ("Read"); Tot_exp+=exp;       Print_elapsed_time (); printf ("read:%llu; total=%llu\n", (unsignedLong Long) exp, (unsignedLong Long) tot_exp); } exit (exit_success);}

Operation Result:

(24) Linux new timer: TIMEFD and related operation function

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.