Linux under Setitimer Timer and timer cancellation __linux

Source: Internet
Author: User
#include <stdio.h> #include <signal.h> #include <time.h> #include <string.h> #include <
    stdlib.h> #include <unistd.h> void Timer_thread (Union Sigval v) {static int i = 0; printf ("Timer_thread function!
    %d\n ", v.sival_int);
printf ("i =%d\n", ++i);  
    int main () {timer_t timerid;  
    struct Sigevent EVP;       memset (&AMP;EVP, 0, sizeof (struct sigevent));                0 Initialize evp.sigev_value.sival_int = 111;                is also the identification timer, the callback function can obtain evp.sigev_notify = Sigev_thread;       The way the thread is notified, a new thread is posted evp.sigev_notify_function = Timer_thread; Thread function Address if (timer_create (Clock_realtime, &AMP;EVP, &timerid) = = 1) {perror ("fail to Timer_c  
        Reate ");  
    Exit (-1); /* The first interval it.it_value so long, after each time is it.it_interval so long, that is it.it_value when 0 will load it.it_interval value * * struct ITIMERSPEC I  
    T  
    It.it_interval.tv_sec = 2;  
 it.it_interval.tv_nsec = 0;   It.it_value.tv_sec = 3;  

    it.it_value.tv_nsec = 0;
        if (Timer_settime (Timerid, 0, &it, NULL) = = 1) {perror ("fail to Timer_settime");
    Exit (-1);
    }//pause ();

    while (1);
return 0; 
 /* * int timer_gettime (timer_t timerid, struct itimerspec *curr_value);
                   * Get the value of the timer specified by Timerid, and fill in curr_value * *

Compile need add:-LRT

Output results:

(Countdown 3 seconds)

Timer_thread function! 111
i = 1
(2s per)
Timer_thread function! 111

i = 2
(2s per)
Timer_thread function! 111
i = 3
(2s per)
Timer_thread function! 111
i = 4



Linux to cancel the timer set with Setitimer
Setitimer set It_interval and It_value to zero:

void Uninit_time ()  
{  
    struct itimerval value;  
    value.it_value.tv_sec = 0;  
    value.it_value.tv_usec = 0;  
    Value.it_interval = Value.it_value;  
    Setitimer (Itimer_real, &value, NULL);  
}

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.