标签:
1 #include<stdio.h> 2 #include<time.h> 3 #include<sys/time.h> 4 #include<unistd.h> 5 #include<stdio.h> 6 #include<time.h> 7 #include<sys/time.h> 8 #include<unistd.h> 9 #include<signal.h> 10 #include<stdlib.h> 11 static void ElsfTimer(int signo ) 12 { 13 struct timeval tp; 14 struct tm *tm; 15 gettimeofday(&tp,NULL); 16 tm=localtime(&tp.tv_sec); 17 printf("Sec=%ld\t",tp.tv_sec); 18 printf("Usec=%ld\t",tp.tv_usec); 19 printf("%d-%d-%d %d:%d:%d\n",tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec); 20 } 21 22 23 static void InitTime(int tv_sec,int tv_usec) 24 { 25 struct itimerval value; 26 27 signal(SIGALRM,ElsfTimer);//注册SIGALRM函数 28 value.it_value.tv_sec=tv_sec; 29 value.it_value.tv_usec=tv_usec; 30 value.it_interval.tv_sec=tv_sec; 31 value.it_interval.tv_usec=tv_usec; 32 setitimer(ITIMER_REAL,&value,NULL); 33 } 34 35 int main() 36 {
37 InitTime(5,0); //设置setitimer的参数 38 struct itimerval ip; 39 getitimer(ITIMER_REAL,&ip);//获取计时器的设置 40 printf("%ld,%ld\n",ip.it_value.tv_sec,ip.it_value.tv_usec);//打印计时器的设置 41 while(1) 42 { 43 printf("Sleeping ++\n"); 44 sleep(1); 45 } 46 exit(0); 47 }
程序运行结果如下:
1 4,999996 //gettitimer获取到的计时器配置 与实际值5s还是有偏差的,说明函数处理计时也不是完全标准! 2 Sleeping ++ 3 Sleeping ++ 4 Sleeping ++ 5 Sleeping ++ 6 Sleeping ++ 7 Sec=1454660611 Usec=533770 2016-2-5 16:23:31 8 Sleeping ++ 9 Sleeping ++ 10 Sleeping ++ 11 Sleeping ++ 12 Sleeping ++ 13 Sec=1454660616 Usec=534003 2016-2-5 16:23:36 14 Sleeping ++ 15 Sleeping ++ 16 Sleeping ++ 17 Sleeping ++ 18 Sleeping ++ 19 Sec=1454660621 Usec=533200 2016-2-5 16:23:41 20 Sleeping ++ 21 Sleeping ++ 22 ^C
可以看到每5s中断函数执行一次
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5183303.html