c语言定时器示例分享

时间:2023-11-04 09:44:52 

在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;
}

标签:c语言,定时器
0
投稿

猜你喜欢

  • android TabLayout使用方法详解

    2021-08-06 07:52:17
  • Java的MD5工具类和客户端测试类

    2022-04-23 03:08:48
  • C#实现Excel导入sqlite的方法

    2021-12-02 23:38:17
  • SpringBoot项目集成xxljob实现全纪录

    2023-01-18 17:26:21
  • servlet实现文件上传、预览、下载、删除功能

    2023-11-16 21:52:48
  • 通过Html网页调用本地安卓(android)app程序代码

    2022-05-10 10:14:34
  • Java String类和StringBuffer类的区别介绍

    2022-06-12 11:42:13
  • Android开发实现简单计算器功能

    2022-10-17 09:18:16
  • 浅谈C#网络编程详解篇

    2022-10-23 04:30:28
  • Java读写文件创建文件夹多种方法示例详解

    2022-11-17 01:08:48
  • Java实现Http工具类的封装操作示例

    2021-08-14 10:27:57
  • 解决IDEA springboot"spring-boot-maven-plugin"报红问题

    2023-08-15 21:29:19
  • SpringCloud实战之Feign声明式服务调用

    2022-07-02 08:25:30
  • 在Framework 4.0中:找出新增的方法与新增的类(一)

    2021-07-07 05:26:07
  • 对WPF中的TreeView实现右键选定

    2022-01-21 00:25:55
  • Android 连接Wifi和创建Wifi热点的实例

    2022-07-16 06:00:52
  • 如何基于SpringBoot实现人脸识别功能

    2022-04-19 13:23:21
  • Android开发简易音乐播放器

    2023-12-26 01:07:03
  • c# 判断指定文件是否存在的简单实现

    2023-10-16 01:39:54
  • java实现两个对象之间传值及简单的封装

    2022-03-11 13:53:18
  • asp之家 软件编程 m.aspxhome.com