システム・プログラム 電子・情報工学系 新城 靖 <yas@is.tsukuba.ac.jp>
このページは、次の URL にあります。
http://www.coins.tsukuba.ac.jp/~yas/coins/syspro-2004/2004-04-26
/time.html
あるいは、次のページから手繰っていくこともできます。
http://www.coins.tsukuba.ac.jp/~yas/
http://www.is.tsukuba.ac.jp/~yas/index-j.html
% egrep time_t /usr/include/bits/types.htypedef long int __time_t; %
![]()
現在の時刻を取得するには、time() システム・コール(System V系)や gettimeofday() システム・コール (BSD系)を使う。
#include <time.h> time_t time(time_t *t); #include <sys/time.h> #include <unistd.h> int gettimeofday(struct timeval *tv, struct timezone *tz);
その秒数からカレンダ的な日付と時刻の形式(struct tm)に変換するライブラ リ関数が、localtime() ライブラリ関数である。struct tm は、次のようなフィー ルドがある。
CTIME(3) Linux Programmer's Manual CTIME(3) #include <time.h> char *asctime(const struct tm *timeptr); 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 *timeptr); ... struct tm { int tm_sec; /* 秒 */ int tm_min; /* 分 */ int tm_hour; /* 時間 */ int tm_mday; /* 日 */ int tm_mon; /* 月 */ int tm_year; /* 年 */ int tm_wday; /* 曜日 */ int tm_yday; /* 年内通算日 */ int tm_isdst; /* 夏時間 */ };
ctime(), strftime() などを使うと、文字列に変換してくれる。逆に、struct tm から time_t を作る関数が mktime() ライブラリ関数である。
localtime() や mktime() は、TZ環境変数(Time Zone)を見ている。閏秒など が混じると単純には計算できない。TZ がセットされていない時、Linux の場 合、/etc/localtime というファイルにあるものが使われる。
% setenv LANG Cプログラムの中で Time Zone を変えることはあまりないが、変えるなら setenv() や putenv() で TZ 環境変数を変えて、tzset() ライブラリ関数を 呼ぶ。% ls -l /etc/localtime
-rw-r--r-- 1 root root 73 Feb 7 2002 /etc/localtime % date
Mon May 12 00:05:41 JST 2003 % setenv TZ EST
% date
Sun May 11 10:05:50 EST 2003 % ls -l /usr/share/zoneinfo/EST
-rw-r--r-- 6 root root 286 Mar 6 09:07 /usr/share/zoneinfo/EST %
![]()
1: /* 2: get-time.c -- 現在の時刻を表示するプログラム 3: ~yas/syspro/time/get-time.c 4: Start: 1998/05/18 22:29:17 5: */ 6: 7: #include <time.h> /* time(2) */ 8: 9: /* 10: Linux: 11: /usr/include/bits/types.h 12: typedef long int __time_t; 13: 14: /usr/include/time.h: 15: typedef __time_t time_t; 16: extern time_t time (time_t *__timer) ; 17: */ 18: 19: main() 20: { 21: time_t t ; 22: t = 0 ; 23: printf("%d: %s",t,ctime(&t) ); 24: t ++ ; 25: printf("%d: %s",t,ctime(&t) ); 26: t = time( 0 ); 27: printf("%d: %s",t,ctime(&t) ); 28: t ++ ; 29: printf("%d: %s",t,ctime(&t) ); 30: }実行例。
% cp ~yas/syspro/time/get-time.c .% make get-time
cc get-time.c -o get-time % ./get-time
0: Wed Dec 31 19:00:00 1969 1: Wed Dec 31 19:00:01 1969 1052670767: Sun May 11 11:32:47 2003 1052670768: Sun May 11 11:32:48 2003 %
![]()