.
[coreutils.git] / lib / gettimeofday.c
blob0d259be1cfa54da27fe631a600ade936e25d2cd7
1 /* Work around the bug in some systems whereby gettimeofday clobbers the
2 static buffer that localtime uses for it's return value. The gettimeofday
3 function from Mac OS X 10.0.4, i.e. Darwin 1.3.7 has this problem.
4 Copyright (C) 2001, 2002 Free Software Foundation, Inc.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software Foundation,
18 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
20 /* written by Jim Meyering */
22 #include <config.h>
24 /* Disable the definitions of gettimeofday and localtime (from config.h)
25 so we can use the library versions here. */
26 #undef gettimeofday
27 #undef localtime
29 #include <sys/types.h>
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
33 # include <time.h>
34 #else
35 # if HAVE_SYS_TIME_H
36 # include <sys/time.h>
37 # else
38 # include <time.h>
39 # endif
40 #endif
42 #include <stdlib.h>
44 static struct tm *localtime_buffer_addr;
46 /* This is a wrapper for localtime. It is used only on systems for which
47 gettimeofday clobbers the static buffer used for localtime's result.
49 On the first call, record the address of the static buffer that
50 localtime uses for its result. */
52 struct tm *
53 rpl_localtime (const time_t *timep)
55 struct tm *tm = localtime (timep);
57 if (! localtime_buffer_addr)
58 localtime_buffer_addr = tm;
60 return tm;
63 /* This is a wrapper for gettimeofday. It is used only on systems for which
64 gettimeofday clobbers the static buffer used for localtime's result.
66 Save and restore the contents of the buffer used for localtime's result
67 around the call to gettimeofday. */
69 int
70 rpl_gettimeofday (struct timeval *tv, struct timezone *tz)
72 struct tm save;
73 int result;
75 if (! localtime_buffer_addr)
77 time_t t = 0;
78 localtime_buffer_addr = localtime (&t);
81 save = *localtime_buffer_addr;
82 result = gettimeofday (tv, tz);
83 *localtime_buffer_addr = save;
85 return result;