linux中创建一个循环定时器(C++)

可以定义一个类来封装定时器的功能,并将其分别放在 `.cpp` 和 `.h` 文件中。这里是一个简化的示例,展示了如何组织这些代码。

假设有一个 `Timer` 类,它负责创建和管理定时器。

Timer.h

#ifndef TIMER_H

#define TIMER_H

#include <signal.h>

#include <time.h>

#include <unistd.h>

class Timer {

public:

Timer();

~Timer();

void start();

void stop();

private:

static void timerCallback(int signum);

static struct sigaction sa;

static struct itimerspec its;

static timer_t timerId;

};

#endif // TIMER_H

```

Timer.cpp

#include "Timer.h"

struct sigaction Timer::sa;

struct itimerspec Timer::its;

timer_t Timer::timerId;

Timer::Timer() {

// 初始化定时器

sa.sa_handler = Timer::timerCallback;

sa.sa_flags = SA_RESTART;

if (sigaction(SIGRTMIN, &sa, NULL) == -1) {

perror("sigaction");

exit(1);

}

struct sigevent sev;

sev.sigev_notify = SIGEV_SIGNAL;

sev.sigev_signo = SIGRTMIN;

sev.sigev_value.sival_ptr = &Timer::timerId;

if (timer_create(CLOCK_REALTIME, &sev, &Timer::timerId) == -1) {

perror("timer_create");

exit(1);

}

its.it_value.tv_sec = 1; // 初始延迟一秒

its.it_value.tv_nsec = 0;

its.it_interval.tv_sec = 1; // 每秒触发

its.it_interval.tv_nsec = 0;

if (timer_settime(Timer::timerId, 0, &its, NULL) == -1) {

perror("timer_settime");

exit(1);

}

}

Timer::~Timer() {

// 销毁定时器

timer_delete(Timer::timerId);

}

void Timer::start() {

while (true) {

pause(); // 等待信号

}

}

void Timer::stop() {

// 停止定时器

timer_settime(Timer::timerId, 0, &its, NULL);

}

void Timer::timerCallback(int signum) {

static int count = 0;

printf("Timer callback called! Count: %d\n", ++count);

}

```

main.cpp

#include "Timer.h"

int main() {

Timer timer;

timer.start();

// 其他代码...

return 0;

}

```

`Timer.h` 包含了 `Timer` 类的声明,`Timer.cpp` 实现了类的方法,包括定时器的创建、启动和停止,以及回调函数。`main.cpp` 中包含了主函数,它实例化 `Timer` 对象并开始定时器。

使用时需要注意信号的安全性和正确性。

相关推荐
笨笨饿25 分钟前
#79_NOP()嵌入式C语言中内联汇编宏的抽象封装模式研究
linux·c语言·网络·驱动开发·算法·硬件工程·个人开发
fish_xk34 分钟前
Linux的权限
linux·运维·服务器
wxin_VXbishe1 小时前
springboot新能源车充电站管理系统小程序-计算机毕业设计源码29213
java·c++·spring boot·python·spring·django·php
嵌入式×边缘AI:打怪升级日志2 小时前
Linux 驱动与应用开发核心自测题库(面试官问答完整版)
linux·运维·php
05候补工程师2 小时前
【408 从零到一】线性表逻辑特征、存储结构对比与 C/C++ 动态内存分配避坑指南
c语言·开发语言·数据结构·c++·考研
怕什么真理无穷3 小时前
C++面试5_ TCP 粘包2(工业级)
开发语言·c++·tcp/ip
努力努力再努力wz3 小时前
【MySQL 进阶系列】拒绝滥用root:从 mysql.user 到权限校验,带你彻底理解用户管理与授权机制!
android·c语言·开发语言·数据结构·数据库·c++·mysql
薛定谔的悦3 小时前
储能充放电状态机执行逻辑详解
linux·数据库·能源·储能·bms
雪度娃娃3 小时前
基于TCP的网络词典
网络·c++·tcp/ip·c#
Sirens.3 小时前
Umami:从Cloud迁移到服务器
运维·服务器