C/C++定时器制作
三種不同精度的睡眠
unsigned int sleep(unsigned int seconds); //睡眠多少秒,睡眠被信號中斷,返回剩余的睡眠時間
int usleep(useconds_t usec);?????//睡眠多少微秒,
int nanosleep(const struct timespec *req,struct timespec *rem);?????//睡眠多少納秒,第一個參數(shù)請求睡眠時間,第二個參數(shù)是剩余多少時間
三種時間結(jié)構(gòu)
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功能強(qiáng)大,支持3種類型的定時器
原型:
int setitimer(int which,const struct itimerval *value,struct itimerval *ovalue);
參數(shù):
第一個參數(shù)which指定定時器類型
第二個參數(shù)是結(jié)構(gòu)體ittimerval的一個實例,結(jié)構(gòu)itimerval形式
第三個參數(shù)可不做處理
返回值:成功返回0,失敗返回-1
第一個參數(shù):
ITIMER_REAL:經(jīng)過指定的時間后,內(nèi)核將發(fā)送SIGALRM信號給本進(jìn)程
ITIMER_VIRTUAL:程序在用戶空間執(zhí)行指定的時間后,內(nèi)核將發(fā)送SIGVTALRM信號給本進(jìn)程
ITIMER_PROF:進(jìn)程在內(nèi)核空間中執(zhí)行時,時間計數(shù)會減少,通常與ITMER_VIRTUAL共用,代表進(jìn)程在用戶空間與內(nèi)核空間中運行指定時間后,內(nèi)核將發(fā)送SIGPROF信號給本進(jìn)程。
#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; //設(shè)置為1秒itv.it_interval.tv_usec = 0; itv.it_value.tv_sec = 1; //設(shè)置1秒后輸出itv.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); //此函數(shù)為linux的api,不是c的標(biāo)準(zhǔn)庫函數(shù) } 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; }?
總結(jié)
以上是生活随笔為你收集整理的C/C++定时器制作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell 获取MD5值
- 下一篇: C/C++面试题—使用STL两个队列实现