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++定时器制作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell 获取MD5值
- 下一篇: C/C++面试题—使用STL两个队列实现