C language timer sample sharing
- 2020-04-02 02:18:14
- OfStack
Developed under Linux, using the C language. For software development that requires timing, it sends out SIGALRM signals in real system time. At regular intervals of one second
C language timer
#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
unsigned int flag; //Timing mark
}
;
struct StructOfTimer
{
struct StructOfTimerStatus testtime; //Test timer
}
mytime;
void SetTimer(int sec,int usec);
void SigalrmFunc(void);
//Timer function
void SigalrmFunc(void)
{
if(mytime.testtime.count++>20) //20 times 50,000 is 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 successn");
}
}
return 0;
}