C/C++定时器制作
三种不同精度的睡眠
unsigned int sleep(unsigned int seconds); //睡眠多少秒,睡眠被信号中断,返回剩余的睡眠时间
int usleep(useconds_t usec); //睡眠多少微秒,
int nanosleep(const struct timespec *req,struct timespec *rem); //睡眠多少纳秒,第一个参数请求睡眠时间,第二个参数是剩余多少时间
三种时间结构
time_t //秒
struct timeval{
long tv_sec; //秒
long tv_usec; //微秒
};
struct timespec{
time_t tv_sec; //秒
long tv_nsec;//纳秒
};
setitmer 定时器的使用
包含头文件<sys/time.h>
功能setitime()比alarm功能强大,支持3种类型的定时器
原型:
int setitimer(int which,const struct itimerval *value,struct itimerval *ovalue);
参数:
第一个参数which指定定时器类型
第二个参数是结构体ittimerval的一个实例,结构itimerval形式
第三个参数可不做处理
返回值:成功返回0,失败返回-1
第一个参数:
ITIMER_REAL:经过指定的时间后,内核将发送SIGALRM信号给本进程
ITIMER_VIRTUAL:程序在用户空间执行指定的时间后,内核将发送SIGVTALRM信号给本进程
ITIMER_PROF:进程在内核空间中执行时,时间计数会减少,通常与ITMER_VIRTUAL共用,代表进程在用户空间与内核空间中运行指定时间后,内核将发送SIGPROF信号给本进程。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/time.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
static int count = 0;
void set_timer()
{
struct itimerval itv;
itv.it_interval.tv_sec = 1; //设置为1秒
itv.it_interval.tv_usec = 0;
itv.it_value.tv_sec = 1; //设置1秒后输出
itv.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &itv, NULL); //此函数为linux的api,不是c的标准库函数
}
void handler(int sig)
{
printf("recv a sig= %d\n",sig);
}
void signal_handler(int m)
{
count ++;
printf("%d\n", count);
}
int main()
{
if(signal(SIGALRM,signal_handler)==SIG_ERR)
{
ERR_EXIT("signal error");
}
set_timer();
for(;;)
{
pause();
}
return 0;
}
相关文章
- 【C/C++学院】(15)QT布局:用户信息
- 【C/C++学院】(4)c++开篇/类和对象/命名空间/类型增强/三目运算符/const专题/引用专题/函数增强
- C语言/C++常见习题问答集锦之移动的坦克
- Open3D(C++) 读取、可视化并保存mesh
- c++模板学习12之通用数组类模板案例封装
- Atitit.upnp SSDP 查找nas的原理与实现java php c#.net c++
- VS中c++文件调用c 函数 ,fatal error C1853 预编译头文件来自编译器的早期版本号,或者预编译头为 C++ 而在 C 中使用它(或相反)
- C++使用技巧(一):解决C++类class C 库函数strcpy使用方法以及出现的报错问题: ‘strcpy’ was not declared in this scope
- 函数调用图工具: Understand(支持Ada, C, C++, C#, Java, FORTRAN, Delphi, Jovial, and PL/M)
- VC++制作DLL具体解释
- Cocos2d-x 3.1.1 学习日志6--30分钟了解C++11新特性
- 排查C++软件异常的常见思路与方法(实战经验总结)
- C++逆向分析——类成员的访问控制
- C++中的异常处理(中)
- 第十三届蓝桥杯 C++ B 组省赛 F 题——统计子矩阵 (AC)
- 13.IDA-显示正确的函数名称(去掉c++后缀命名)
- ❤️ C++ 用户输入讲解教程❤️
- 【C++】内存管理常见面试题
- C++堆内存错误:CRT detected that the application wrote to memory after end of heap buffer
- VC++中视频采集系统(摄像头的制作,串口通信的应用)