在多线程的应用中要用到延时函数,开始时我只用到 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有两个成员,一个是秒,一个是微妙。
- struct timeval {
- long tv_sec; /**//* seconds */
- long tv_usec; /**//* microseconds */
- ;
(3)struct timespec有两个成员,一个是秒,一个是纳秒。
- struct timespec{
- time_t tv_sec; /**//* seconds */
- long tv_nsec; /**//* nanoseconds */
- };
(4)struct tm是直观意义上的时间表示方法:
- struct tm {
- int tm_sec; /**//* seconds */
- int tm_min; /**//* minutes */
- int tm_hour; /**//* hours */
- int tm_mday; /**//* day of the month */
- int tm_mon; /**//* month */
- int tm_year; /**//* year */
- int tm_wday; /**//* day of the week */
- int tm_yday; /**//* day in the year */
- int tm_isdst; /**//* daylight saving time */
- };
2、 时间操作 (1) 时间格式间的转换函数 主要是 time_t、struct tm、时间的字符串格式之间的转换。看下面的函数参数类型以及返回值类型:
- char *asctime(const struct tm *tm);
- char *ctime(const time_t *timep);
- struct tm *gmtime(const time_t *timep);
- struct tm *localtime(const time_t *timep);
- time_t mktime(struct tm *tm);
gmtime和localtime的参数以及返回值类型相同,区别是前者返回的格林威治标准时间,后者是当地时间。 (2) 获取时间函数 两个函数,获取的时间类型看原型就知道了:
- time_t time(time_t *t);
- int gettimeofday(struct timeval *tv, struct timezone *tz);
前者获取time_t类型,后者获取struct timeval类型,因为类型的缘故,前者只能精确到秒,后者可以精确到微秒。