zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C/C++定时器制作

C++ 制作 定时器
2023-09-11 14:14:44 时间

三种不同精度的睡眠

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