其他分享
首页 > 其他分享> > 有关时间函数的使用time()

有关时间函数的使用time()

作者:互联网

三种不同精度的睡眠

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)

void handler(int sig);
int main()
{
	if(signal(SIGALRM,handler)==SIG_ERR)
	{
		ERR_EXIT("signal error");
	}
	struct timeval tv_interval = {1,0};
	struct timeval tv_value = {5,0};
	struct itimerval it;
	it.it_interval = tv_interval;
	it.it_value = tv_value;
	setitimer(ITIMER_REAL,&it,NULL);

	for(;;)
	{
		pause();
	}
	return 0;	
}
void handler(int sig)
{
	printf("recv a sig= %d\n",sig);
	
}

 

结果:

这行代码执行之后,第一行是隔了5秒才输出的,剩下了每个1秒输出一次。

	struct timeval tv_interval = {1,0};
	struct timeval tv_value = {5,0};

就只这两行代码的原因。

 

标签:struct,tv,有关,value,timeval,int,time,include,函数
来源: https://blog.csdn.net/m0_38036750/article/details/86498621