c语言定时器 c语言定时器示例分享

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c语言定时器 c语言定时器示例分享

  2021-03-19 我要评论
想了解c语言定时器示例讲解的相关内容吗,在本文为您仔细讲解c语言定时器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c语言,定时器,下面大家一起来学习吧。

在linux下开发,使用的是C语言。适用于需要定时的软件开发,以系统真实的时间来计算,它送出SIGALRM信号。每隔一秒定时一次

c语言定时器

复制代码 代码如下:

#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;                               //计数值
    unsigned int flag;                                //定时标志
}
;

struct StructOfTimer

    struct StructOfTimerStatus      testtime;   //测试定时器
}
mytime;

 

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


//定时器函数
/*******************************************************************************
* Discription:SIGALRM 信号响应函数;用作定时器
* Input      :
* Output    :
*******************************************************************************/
void SigalrmFunc(void)
{
    if(mytime.testtime.count++>20)      //定时1秒,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;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们