一、三种不同精度的睡眠
函数声明:
#include <unistd.h>函数参数:
unsigned int sleep(unsigned int seconds);
int usleep(useconds_t usec);
#include <time.h>
int nanosleep(const struct timespec *req, struct timespec *rem);
秒、微秒、纳秒
返回值:
返回剩余要睡眠的时间(睡眠的时候有可能被信号打断)
系统调用nanosleep成功返回0,失败返回-1
二、三种时间结构
1、
time_t
2、
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
3、
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
三、setitimer和getitimer
函数功能:
setitimer()比alarm功能强大,支持3种类型的定时器
函数声明:
#include <sys/time.h>
int getitimer(int which, struct itimerval *curr_value);
int setitimer(int which, const struct itimerval *new_value,struct itimerval *old_value);
函数参数:
第一个参数which指定定时器类型
- ITIMER_REAL:经过指定的时间后,内核将发送SIGALRM信号给本进程
- ITIMER_VIRTUAL :程序在用户空间执行指定的时间后,内核将发送SIGVTALRM信号给本进程
- ITIMER_PROF :进程在内核空间中执行时,时间计数会减少,通常与ITIMER_VIRTUAL共用,代表进程在用户空间与内核空间中运行指定时间后,内核将发送SIGPROF信号给本进程。
第二个参数是结构itimerval的一个实例,结构itimerval形式
第三个参数可不做处理,表示当前时钟还剩余的时间(里下一次产生信号的时间)。
返回值:
成功返回0失败返回-1
示例:
#include <sys/types.h>在这个例子中tv_interval和tv_value的不同是后者是第一次产生信号的等待事件,前者是产生信号之间的时间间隔。
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
void handle(int sig);
int main(int argc,char* argv[])
{
if (signal(SIGALRM,handle) == SIG_ERR)
ERR_EXIT("signal error");
struct timeval tv_interval = {1,0};
struct timeval tv_value = {1,0};
struct itimerval it;
it.it_interval = tv_interval;
it.it_value = tv_value;
setitimer(ITIMER_REAL,&it,NULL);
for(;;)
pause();
return 0;
}
void handle(int sig)
{
printf("recv a sig=%d\n",sig);
}