Unix C 延时函数小结


在多线程的应用中要用到延时函数,开始时我只用到 sleep 这个秒级函数,但在 solaris  上跑时,程序运行到sleep时,却显示 “Alarm clock” 这句话后就中止了。据说是产生了 alarm 这个信号,而系统默认信号处理就是中止程序,所以要在程序中把这个设置为忽略:

signal(SIGALRM, SIG_IGN); 

Unix 上的延时函数有好几种:

一、 基础知识
1、时间类型。Linux下常用的时间类型有4个:time_t,struct timeval,struct timespec,struct tm。
(1)time_t是一个长整型,一般用来表示用1970年以来的秒数。
(2)Struct timeval有两个成员,一个是秒,一个是微妙。

  1. struct timeval {   
  2.    long tv_sec;        /**//* seconds */  
  3.    long tv_usec;  /**//* microseconds */  
  4. ;  

(3)struct timespec有两个成员,一个是秒,一个是纳秒。

  1. struct timespec{   
  2.     time_t  tv_sec;         /**//* seconds */  
  3.     long    tv_nsec;        /**//* nanoseconds */  
  4. };  

(4)struct tm是直观意义上的时间表示方法:

  1. struct tm {   
  2.     int     tm_sec;         /**//* seconds */  
  3.     int     tm_min;         /**//* minutes */  
  4.     int     tm_hour;        /**//* hours */  
  5.     int     tm_mday;        /**//* day of the month */  
  6.     int     tm_mon;         /**//* month */  
  7.     int     tm_year;        /**//* year */  
  8.     int     tm_wday;        /**//* day of the week */  
  9.     int     tm_yday;        /**//* day in the year */  
  10.     int     tm_isdst;       /**//* daylight saving time */  
  11. };  

2、 时间操作

(1) 时间格式间的转换函数

主要是 time_t、struct tm、时间的字符串格式之间的转换。看下面的函数参数类型以及返回值类型:

  1. char *asctime(const struct tm *tm);   
  2. char *ctime(const time_t *timep);   
  3. struct tm *gmtime(const time_t *timep);   
  4. struct tm *localtime(const time_t *timep);   
  5. time_t mktime(struct tm *tm);  

gmtime和localtime的参数以及返回值类型相同,区别是前者返回的格林威治标准时间,后者是当地时间。

(2) 获取时间函数

两个函数,获取的时间类型看原型就知道了:

  1. time_t time(time_t *t);   
  2. int gettimeofday(struct timeval *tv, struct timezone *tz);  

前者获取time_t类型,后者获取struct timeval类型,因为类型的缘故,前者只能精确到秒,后者可以精确到微秒。

  • 1
  • 2
  • 下一页

相关内容