C-language Timer sample sharing _c language

Source: Internet
Author: User

Developed under Linux, the C language is used. It is suitable for the software development that needs to be timed, it sends out the SIGALRM signal with the real time of the system. Timed every second.

C Language Timer

Copy Code code as follows:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "Pthread.h"
#include <netinet/in.h>
#include <signal.h>
#include <sys/time.h>


struct Structoftimerstatus
{
unsigned int count; Count value
unsigned int flag; Timing Flag
}
;

struct Structoftimer
{
struct Structoftimerstatus testtime; Test timer
}
MyTime;

void SetTimer (int sec,int usec);
void Sigalrmfunc (void);


//Timer function
/*******************************************************************************
* DISCRIPTION:SIGALRM signal response function; use as Timer
* input     :
* output   :
* * * /
void Sigalrmfunc (void)
{
    if (mytime.testtime.count++>20)      //timed 1 seconds, 20*50000=1s
     {
        mytime.testtime.flag=1;
        mytime.testtime.count=0;
   }
}


void SetTimer (int sec,int usec)
{
    struct itimerval value,ovalue;
    Signal (SIGALRM, (void *) sigalrmfunc);

    value.it_value.tv_sec = sec;
    value.it_value.tv_usec = usec;
    value.it_interval.tv_sec = sec;
    value.it_interval.tv_usec = usec;

    Setitimer (itimer_real,&value,&ovalue);  
}

int main (int argc, char **argv)
{
SetTimer (0, 50000);
while (1)
{
if (Mytime.testtime.flag = 1)
{
Mytime.testtime.flag = 0;
System ("clear");
printf ("Timing success\n");
}
}
return 0;
}

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.