1@node Date and Time, Resource Usage And Limitation, Arithmetic, Top
2@c %MENU% Functions for getting the date and time and formatting them nicely
3@chapter Date and Time
4
5This chapter describes functions for manipulating dates and times,
6including functions for determining what time it is and conversion
7between different time representations.
8
9@menu
10* Time Basics::                 Concepts and definitions.
11* Time Types::                  Data types to represent time.
12* Calculating Elapsed Time::    How to calculate the length of an interval.
13* Processor And CPU Time::      Time a program has spent executing.
14* Calendar Time::               Manipulation of ``real'' dates and times.
15* Setting an Alarm::            Sending a signal after a specified time.
16* Sleeping::                    Waiting for a period of time.
17@end menu
18
19
20@node Time Basics
21@section Time Basics
22@cindex time
23
24Discussing time in a technical manual can be difficult because the word
25``time'' in English refers to lots of different things.  In this manual,
26we use a rigorous terminology to avoid confusion, and the only thing we
27use the simple word ``time'' for is to talk about the abstract concept.
28
29A @dfn{calendar time} is a point in the time continuum, for example
30November 4, 1990, at 18:02.5 UTC.  Sometimes this is called ``absolute
31time''.
32@cindex calendar time
33
34We don't speak of a ``date'', because that is inherent in a calendar
35time.
36@cindex date
37
38An @dfn{interval} is a contiguous part of the time continuum between two
39calendar times, for example the hour between 9:00 and 10:00 on July 4,
401980.
41@cindex interval
42
43An @dfn{elapsed time} is the length of an interval, for example, 35
44minutes.  People sometimes sloppily use the word ``interval'' to refer
45to the elapsed time of some interval.
46@cindex elapsed time
47@cindex time, elapsed
48
49An @dfn{amount of time} is a sum of elapsed times, which need not be of
50any specific intervals.  For example, the amount of time it takes to
51read a book might be 9 hours, independently of when and in how many
52sittings it is read.
53
54A @dfn{period} is the elapsed time of an interval between two events,
55especially when they are part of a sequence of regularly repeating
56events.
57@cindex period of time
58
59A @dfn{simple calendar time} is a calendar time represented as an
60elapsed time since a fixed, implementation-specific calendar time
61called the @dfn{epoch}.  This representation is convenient for doing
62calculations on calendar times, such as finding the elapsed time
63between two calendar times.  Simple calendar times are independent of
64time zone; they represent the same instant in time regardless of where
65on the globe the computer is.
66
67POSIX says that simple calendar times do not include leap seconds, but
68some (otherwise POSIX-conformant) systems can be configured to include
69leap seconds in simple calendar times.
70@cindex leap seconds
71@cindex seconds, leap
72@cindex simple time
73@cindex simple calendar time
74@cindex calendar time, simple
75@cindex epoch
76
77A @dfn{broken-down time} is a calendar time represented by its
78components in the Gregorian calendar: year, month, day, hour, minute,
79and second.  A broken-down time value is relative to a specific time
80zone, and so it is also sometimes called a @dfn{local time}.
81Broken-down times are most useful for input and output, as they are
82easier for people to understand, but more difficult to calculate with.
83@cindex broken-down time
84@cindex local time
85@cindex Gregorian calendar
86@cindex calendar, Gregorian
87
88@dfn{CPU time} measures the amount of time that a single process has
89actively used a CPU to perform computations.  It does not include the
90time that process has spent waiting for external events.  The system
91tracks the CPU time used by each process separately.
92@cindex CPU time
93
94@dfn{Processor time} measures the amount of time @emph{any} CPU has
95been in use by @emph{any} process.  It is a basic system resource,
96since there's a limit to how much can exist in any given interval (the
97elapsed time of the interval times the number of CPUs in the computer)
98
99People often call this CPU time, but we reserve the latter term in
100this manual for the definition above.
101@cindex processor time
102
103@node Time Types
104@section Time Types
105
106ISO C and POSIX define several data types for representing elapsed
107times, simple calendar times, and broken-down times.
108
109@deftp {Data Type} clock_t
110@standards{ISO, time.h}
111@code{clock_t} is used to measure processor and CPU time.
112It may be an integer or a floating-point type.
113Its values are counts of @dfn{clock ticks} since some arbitrary event
114in the past.
115The number of clock ticks per second is system-specific.
116@xref{Processor And CPU Time}, for further detail.
117@cindex clock ticks
118@cindex ticks, clock
119@end deftp
120
121@deftp {Data Type} time_t
122@standards{ISO, time.h}
123@code{time_t} is the simplest data type used to represent simple
124calendar time.
125
126In ISO C, @code{time_t} can be either an integer or a floating-point
127type, and the meaning of @code{time_t} values is not specified.  The
128only things a strictly conforming program can do with @code{time_t}
129values are: pass them to @code{difftime} to get the elapsed time
130between two simple calendar times (@pxref{Calculating Elapsed Time}),
131and pass them to the functions that convert them to broken-down time
132(@pxref{Broken-down Time}).
133
134On POSIX-conformant systems, @code{time_t} is an integer type and its
135values represent the number of seconds elapsed since the @dfn{epoch},
136which is 00:00:00 on January 1, 1970, Coordinated Universal Time.
137
138@Theglibc{} additionally guarantees that @code{time_t} is a signed
139type, and that all of its functions operate correctly on negative
140@code{time_t} values, which are interpreted as times before the epoch.
141@cindex epoch
142@end deftp
143
144@deftp {Data Type} {struct timespec}
145@standards{POSIX.1, time.h}
146@cindex timespec
147@code{struct timespec} represents a simple calendar time, or an
148elapsed time, with sub-second resolution.  It is declared in
149@file{time.h} and has the following members:
150
151@table @code
152@item time_t tv_sec
153The number of whole seconds elapsed since the epoch (for a simple
154calendar time) or since some other starting point (for an elapsed
155time).
156
157@item long int tv_nsec
158The number of nanoseconds elapsed since the time given by the
159@code{tv_sec} member.
160
161When @code{struct timespec} values are produced by @glibcadj{}
162functions, the value in this field will always be greater than or
163equal to zero, and less than 1,000,000,000.
164When @code{struct timespec} values are supplied to @glibcadj{}
165functions, the value in this field must be in the same range.
166@end table
167@end deftp
168
169@deftp {Data Type} {struct timeval}
170@standards{BSD, sys/time.h}
171@cindex timeval
172@code{struct timeval} is an older type for representing a simple
173calendar time, or an elapsed time, with sub-second resolution. It is
174almost the same as @code{struct timespec}, but provides only
175microsecond resolution.  It is declared in @file{sys/time.h} and has
176the following members:
177
178@table @code
179@item time_t tv_sec
180The number of whole seconds elapsed since the epoch (for a simple
181calendar time) or since some other starting point (for an elapsed
182time).
183
184@item long int tv_usec
185The number of microseconds elapsed since the time given by the
186@code{tv_sec} member.
187
188When @code{struct timeval} values are produced by @glibcadj{}
189functions, the value in this field will always be greater than or
190equal to zero, and less than 1,000,000.
191When @code{struct timeval} values are supplied to @glibcadj{}
192functions, the value in this field must be in the same range.
193@end table
194@end deftp
195
196@deftp {Data Type} {struct tm}
197@standards{ISO, time.h}
198This is the data type used to represent a broken-down time.  It has
199separate fields for year, month, day, and so on.
200@xref{Broken-down Time}, for further details.
201@end deftp
202
203@node Calculating Elapsed Time
204@section Calculating Elapsed Time
205
206Often, one wishes to calculate an elapsed time as the difference
207between two simple calendar times.  @Theglibc{} provides only one
208function for this purpose.
209
210@deftypefun double difftime (time_t @var{end}, time_t @var{begin})
211@standards{ISO, time.h}
212@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
213The @code{difftime} function returns the number of seconds of elapsed
214time from calendar time @var{begin} to calendar time @var{end}, as
215a value of type @code{double}.
216
217On POSIX-conformant systems, the advantage of using
218@samp{difftime (@var{end}, @var{begin})} over @samp{@var{end} - @var{begin}}
219is that it will produce the mathematically correct result even if
220@var{end} and @var{begin} are so far apart that a simple subtraction
221would overflow.  However, if they are so far apart that a @code{double}
222cannot exactly represent the difference, the result will be inexact.
223
224On other systems, @code{time_t} values might be encoded in a way that
225prevents subtraction from working directly, and then @code{difftime}
226would be the only way to compute their difference.
227@end deftypefun
228
229@Theglibc{} does not provide any functions for computing the
230difference between two values of type @w{@code{struct timeval}} or
231@w{@code{struct timespec}}.  Here is the recommended way to do this
232calculation by hand.  It works even on some peculiar operating systems
233where the @code{tv_sec} member has an unsigned type.
234
235@smallexample
236@include timeval_subtract.c.texi
237@end smallexample
238
239@node Processor And CPU Time
240@section Processor And CPU Time
241
242If you're trying to optimize your program or measure its efficiency,
243it's very useful to know how much processor time it uses.  For that,
244calendar time and elapsed times are useless because a process may spend
245time waiting for I/O or for other processes to use the CPU.  However,
246you can get the information with the functions in this section.
247
248CPU time (@pxref{Time Basics}) is represented by the data type
249@code{clock_t}, which is a number of @dfn{clock ticks}.  It gives the
250total amount of time a process has actively used a CPU since some
251arbitrary event.  On @gnusystems{}, that event is the creation of the
252process.  While arbitrary in general, the event is always the same event
253for any particular process, so you can always measure how much time on
254the CPU a particular computation takes by examining the process' CPU
255time before and after the computation.
256@cindex CPU time
257@cindex clock ticks
258@cindex ticks, clock
259
260On @gnulinuxhurdsystems{}, @code{clock_t} is equivalent to @code{long int} and
261@code{CLOCKS_PER_SEC} is an integer value.  But in other systems, both
262@code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer
263or floating-point types.  Casting CPU time values to @code{double}, as
264in the example above, makes sure that operations such as arithmetic and
265printing work properly and consistently no matter what the underlying
266representation is.
267
268Note that the clock can wrap around.  On a 32bit system with
269@code{CLOCKS_PER_SEC} set to one million this function will return the
270same value approximately every 72 minutes.
271
272For additional functions to examine a process' use of processor time,
273and to control it, see @ref{Resource Usage And Limitation}.
274
275
276@menu
277* CPU Time::                    The @code{clock} function.
278* Processor Time::              The @code{times} function.
279@end menu
280
281@node CPU Time
282@subsection CPU Time Inquiry
283
284To get a process' CPU time, you can use the @code{clock} function.  This
285facility is declared in the header file @file{time.h}.
286@pindex time.h
287
288In typical usage, you call the @code{clock} function at the beginning
289and end of the interval you want to time, subtract the values, and then
290divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second)
291to get processor time, like this:
292
293@smallexample
294@group
295#include <time.h>
296
297clock_t start, end;
298double cpu_time_used;
299
300start = clock();
301@dots{} /* @r{Do the work.} */
302end = clock();
303cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
304@end group
305@end smallexample
306
307Do not use a single CPU time as an amount of time; it doesn't work that
308way.  Either do a subtraction as shown above or query processor time
309directly.  @xref{Processor Time}.
310
311Different computers and operating systems vary wildly in how they keep
312track of CPU time.  It's common for the internal processor clock
313to have a resolution somewhere between a hundredth and millionth of a
314second.
315
316@deftypevr Macro int CLOCKS_PER_SEC
317@standards{ISO, time.h}
318The value of this macro is the number of clock ticks per second measured
319by the @code{clock} function.  POSIX requires that this value be one
320million independent of the actual resolution.
321@end deftypevr
322
323@deftypefun clock_t clock (void)
324@standards{ISO, time.h}
325@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
326@c On Hurd, this calls task_info twice and adds user and system time
327@c from both basic and thread time info structs.  On generic posix,
328@c calls times and adds utime and stime.  On bsd, calls getrusage and
329@c safely converts stime and utime to clock.  On linux, calls
330@c clock_gettime.
331This function returns the calling process' current CPU time.  If the CPU
332time is not available or cannot be represented, @code{clock} returns the
333value @code{(clock_t)(-1)}.
334@end deftypefun
335
336
337@node Processor Time
338@subsection Processor Time Inquiry
339
340The @code{times} function returns information about a process'
341consumption of processor time in a @w{@code{struct tms}} object, in
342addition to the process' CPU time.  @xref{Time Basics}.  You should
343include the header file @file{sys/times.h} to use this facility.
344@cindex processor time
345@cindex CPU time
346@pindex sys/times.h
347
348@deftp {Data Type} {struct tms}
349@standards{POSIX.1, sys/times.h}
350The @code{tms} structure is used to return information about process
351times.  It contains at least the following members:
352
353@table @code
354@item clock_t tms_utime
355This is the total processor time the calling process has used in
356executing the instructions of its program.
357
358@item clock_t tms_stime
359This is the processor time the system has used on behalf of the calling
360process.
361
362@item clock_t tms_cutime
363This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
364values of all terminated child processes of the calling process, whose
365status has been reported to the parent process by @code{wait} or
366@code{waitpid}; see @ref{Process Completion}.  In other words, it
367represents the total processor time used in executing the instructions
368of all the terminated child processes of the calling process, excluding
369child processes which have not yet been reported by @code{wait} or
370@code{waitpid}.
371@cindex child process
372
373@item clock_t tms_cstime
374This is similar to @code{tms_cutime}, but represents the total processor
375time the system has used on behalf of all the terminated child processes
376of the calling process.
377@end table
378
379All of the times are given in numbers of clock ticks.  Unlike CPU time,
380these are the actual amounts of time; not relative to any event.
381@xref{Creating a Process}.
382@end deftp
383
384@deftypevr Macro int CLK_TCK
385@standards{POSIX.1, time.h}
386This is an obsolete name for the number of clock ticks per second.  Use
387@code{sysconf (_SC_CLK_TCK)} instead.
388@end deftypevr
389
390@deftypefun clock_t times (struct tms *@var{buffer})
391@standards{POSIX.1, sys/times.h}
392@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
393@c On HURD, this calls task_info twice, for basic and thread times info,
394@c adding user and system times into tms, and then gettimeofday, to
395@c compute the real time.  On BSD, it calls getclktck, getrusage (twice)
396@c and time.  On Linux, it's a syscall with special handling to account
397@c for clock_t counts that look like error values.
398The @code{times} function stores the processor time information for
399the calling process in @var{buffer}.
400
401The return value is the number of clock ticks since an arbitrary point
402in the past, e.g. since system start-up.  @code{times} returns
403@code{(clock_t)(-1)} to indicate failure.
404@end deftypefun
405
406@strong{Portability Note:} The @code{clock} function described in
407@ref{CPU Time} is specified by the @w{ISO C} standard.  The
408@code{times} function is a feature of POSIX.1.  On @gnusystems{}, the
409CPU time is defined to be equivalent to the sum of the @code{tms_utime}
410and @code{tms_stime} fields returned by @code{times}.
411
412@node Calendar Time
413@section Calendar Time
414
415This section describes the functions for getting, setting, and
416manipulating calendar times.
417
418@menu
419* Getting the Time::            Functions for finding out what time it is.
420* Setting and Adjusting the Time::
421                                Functions for setting and adjusting
422                                  the system clock.
423* Broken-down Time::            Facilities for manipulating local time.
424* Formatting Calendar Time::    Converting times to strings.
425* Parsing Date and Time::       Convert textual time and date information back
426                                 into broken-down time values.
427* TZ Variable::                 How users specify the time zone.
428* Time Zone Functions::         Functions to examine or specify the time zone.
429* Time Functions Example::      An example program showing use of some of
430				 the time functions.
431@end menu
432
433@node Getting the Time
434@subsection Getting the Time
435
436@Theglibc{} provides several functions for getting the current
437calendar time, with different levels of resolution.
438
439@deftypefun time_t time (time_t *@var{result})
440@standards{ISO, time.h}
441@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
442This is the simplest function for getting the current calendar time.
443It returns the calendar time as a value of type @code{time_t}; on
444POSIX systems, that means it has a resolution of one second.  It
445uses the same clock as @w{@samp{clock_gettime (CLOCK_REALTIME_COARSE)}},
446when the clock is available or @w{@samp{clock_gettime (CLOCK_REALTIME)}}
447otherwise.
448
449If the argument @var{result} is not a null pointer, the calendar time
450value is also stored in @code{*@var{result}}.
451
452This function cannot fail.
453@end deftypefun
454
455Some applications need more precise timekeeping than is possible with
456a @code{time_t} alone.  Some applications also need more control over
457what is meant by ``the current time.''  For these applications, POSIX
458provides a function @code{clock_gettime} that can retrieve the time
459with up to nanosecond precision, from a variety of different clocks.
460Clocks can be system-wide, measuring time the same for all processes;
461or they can be per-process or per-thread, measuring CPU time consumed
462by a particular process, or some other similar resource.  Each clock
463has its own resolution and epoch.  You can find the resolution of a
464clock with the function @code{clock_getres}.  There is no function to
465get the epoch for a clock; either it is fixed and documented, or the
466clock is not meant to be used to measure absolute times.
467
468@deftp {Data Type} clockid_t
469@standards{POSIX.1, time.h}
470The type @code{clockid_t} is used for constants that indicate which of
471several system clocks one wishes to use.
472@end deftp
473
474All systems that support this family of functions will define at least
475this clock constant:
476
477@deftypevr Macro clockid_t CLOCK_REALTIME
478@standards{POSIX.1, time.h}
479This clock uses the POSIX epoch, 00:00:00 on January 1, 1970, Coordinated
480Universal Time. It is close to, but not necessarily in lock-step with, the
481clocks of @code{time} (above) and of @code{gettimeofday} (below).
482@end deftypevr
483
484@cindex monotonic time
485A second clock constant which is not universal, but still very common,
486is for a clock measuring @dfn{monotonic time}.  Monotonic time is
487useful for measuring elapsed times, because it guarantees that those
488measurements are not affected by changes to the system clock.
489
490@deftypevr Macro clockid_t CLOCK_MONOTONIC
491@standards{POSIX.1, time.h}
492System-wide clock that continuously measures the advancement of
493calendar time, ignoring discontinuous changes to the system's
494setting for absolute calendar time.
495
496The epoch for this clock is an unspecified point in the past.
497The epoch may change if the system is rebooted or suspended.
498Therefore, @code{CLOCK_MONOTONIC} cannot be used to measure
499absolute time, only elapsed time.
500@end deftypevr
501
502Systems may support more than just these two clocks.
503
504@deftypefun int clock_gettime (clockid_t @var{clock}, struct timespec *@var{ts})
505@standards{POSIX.1, time.h}
506Get the current time accoding to the clock identified by @var{clock},
507storing it as seconds and nanoseconds in @code{*@var{ts}}.
508@xref{Time Types}, for a description of @code{struct timespec}.
509
510The return value is @code{0} on success and @code{-1} on failure.  The
511following @code{errno} error condition is defined for this function:
512
513@table @code
514@item EINVAL
515The clock identified by @var{clock} is not supported.
516@end table
517@end deftypefun
518
519@code{clock_gettime} reports the time scaled to seconds and
520nanoseconds, but the actual resolution of each clock may not be as
521fine as one nanosecond, and may not be the same for all clocks.  POSIX
522also provides a function for finding out the actual resolution of a
523clock:
524
525@deftypefun int clock_getres (clockid_t @var{clock}, struct timespec *@var{res})
526@standards{POSIX.1, time.h}
527Get the actual resolution of the clock identified by @var{clock},
528storing it in @code{*@var{ts}}.
529
530For instance, if the clock hardware for @code{CLOCK_REALTIME}
531uses a quartz crystal that oscillates at 32.768 kHz,
532then its resolution would be 30.518 microseconds,
533and @w{@samp{clock_getres (CLOCK_REALTIME, &r)}} would set
534@code{r.tv_sec} to 0 and @code{r.tv_nsec} to 30518.
535
536The return value is @code{0} on success and @code{-1} on failure.  The
537following @code{errno} error condition is defined for this function:
538
539@table @code
540@item EINVAL
541The clock identified by @var{clock} is not supported.
542@end table
543@end deftypefun
544
545These functions, and the constants that identify particular clocks,
546are declared in @file{time.h}.
547
548@strong{Portability Note:} On some systems, including systems that use
549older versions of @theglibc{}, programs that use @code{clock_gettime}
550or @code{clock_setres} must be linked with the @code{-lrt} library.
551This has not been necessary with @theglibc{} since version 2.17.
552
553@Theglibc{} also provides an older, but still widely used, function
554for getting the current time with a resolution of microseconds.  This
555function is declared in @file{sys/time.h}.
556
557@deftypefun int gettimeofday (struct timeval *@var{tp}, void *@var{tzp})
558@standards{BSD, sys/time.h}
559@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
560Get the current calendar time, storing it as seconds and microseconds
561in @code{*@var{tp}}.  @xref{Time Types}, for a description of
562@code{struct timeval}.  The clock of @code{gettimeofday} is close to,
563but not necessarily in lock-step with, the clocks of @code{time} and of
564@w{@samp{clock_gettime (CLOCK_REALTIME)}} (see above).
565
566On some historic systems, if @var{tzp} was not a null pointer,
567information about a system-wide time zone would be written to
568@code{*@var{tzp}}.  This feature is obsolete and not supported on
569@gnusystems{}.  You should always supply a null pointer for this
570argument.  Instead, use the facilities described in @ref{Time Zone
571Functions} and in @ref{Broken-down Time} for working with time zones.
572
573This function cannot fail, and its return value is always @code{0}.
574
575@strong{Portability Note:} As of the 2008 revision of POSIX, this
576function is considered obsolete.  @Theglibc{} will continue to provide
577this function indefinitely, but new programs should use
578@code{clock_gettime} instead.
579@end deftypefun
580
581@node Setting and Adjusting the Time
582@subsection Setting and Adjusting the Time
583
584The clock hardware inside a modern computer is quite reliable, but it
585can still be wrong.  The functions in this section allow one to set
586the system's idea of the current calendar time, and to adjust the rate
587at which the system counts seconds, so that the calendar time will
588both be accurate, and remain accurate.
589
590The functions in this section require special privileges to use.
591@xref{Users and Groups}.
592
593@deftypefun int clock_settime (clockid_t @var{clock}, const struct timespec *@var{ts})
594@standards{POSIX, time.h}
595@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
596Change the current calendar time, according to the clock identified by
597@var{clock}, to be the simple calendar time in @code{*@var{ts}}.
598
599Not all of the system's clocks can be changed.  For instance, the
600@code{CLOCK_REALTIME} clock can be changed (with the appropriate
601privileges), but the @code{CLOCK_MONOTONIC} clock cannot.
602
603Because simple calendar times are independent of time zone, this
604function should not be used when the time zone changes (e.g.@: if the
605computer is physically moved from one zone to another).  Instead, use
606the facilities described in @ref{Time Zone Functions}.
607
608@code{clock_settime} causes the clock to jump forwards or backwards,
609which can cause a variety of problems.  Changing the
610@code{CLOCK_REALTIME} clock with @code{clock_settime} does not affect
611when timers expire (@pxref{Setting an Alarm}) or when sleeping
612processes wake up (@pxref{Sleeping}), which avoids some of the
613problems.  Still, for small changes made while the system is running,
614it is better to use @code{ntp_adjtime} (below) to make a smooth
615transition from one time to another.
616
617The return value is @code{0} on success and @code{-1} on failure.  The
618following @code{errno} error conditions are defined for this function:
619
620@table @code
621@item EINVAL
622The clock identified by @var{clock} is not supported or cannot be set
623at all, or the simple calendar time in @code{*@var{ts}} is invalid
624(for instance, @code{ts->tv_nsec} is negative or greater than 999,999,999).
625
626@item EPERM
627This process does not have the privileges required to set the clock
628identified by @var{clock}.
629@end table
630
631@strong{Portability Note}: On some systems, including systems that use
632older versions of @theglibc{}, programs that use @code{clock_settime}
633must be linked with the @code{-lrt} library.  This has not been
634necessary with @theglibc{} since version 2.17.
635@end deftypefun
636
637@cindex time, high precision
638@cindex clock, high accuracy
639@cindex clock, disciplining
640@pindex sys/timex.h
641For systems that remain up and running for long periods, it is not
642enough to set the time once; one should also @dfn{discipline} the
643clock so that it does not drift away from the true calendar time.
644
645The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
646interface to monitor and discipline the system clock.  For example,
647you can fine-tune the rate at which the clock ``ticks,'' and make
648small adjustments to the current reported calendar time smoothly, by
649temporarily speeding up or slowing down the clock.
650
651These functions' names begin with @samp{ntp_} because they were
652designed for use by programs implementing the Network Time Protocol to
653synchronize a system's clock with other systems' clocks and/or with
654external high-precision clock hardware.
655
656These functions, and the constants and structures they use, are
657declared in @file{sys/timex.h}.
658
659@tindex struct ntptimeval
660@deftp {Data Type} {struct ntptimeval}
661This structure is used to report information about the system clock.
662It contains the following members:
663@table @code
664@item struct timeval time
665The current calendar time, as if retrieved by @code{gettimeofday}.
666The @code{struct timeval} data type is described in
667@ref{Time Types}.
668
669@item long int maxerror
670This is the maximum error, measured in microseconds.  Unless updated
671via @code{ntp_adjtime} periodically, this value will reach some
672platform-specific maximum value.
673
674@item long int esterror
675This is the estimated error, measured in microseconds.  This value can
676be set by @code{ntp_adjtime} to indicate the estimated offset of the
677system clock from the true calendar time.
678@end table
679@end deftp
680
681@deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
682@standards{GNU, sys/timex.h}
683@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
684@c Wrapper for adjtimex.
685The @code{ntp_gettime} function sets the structure pointed to by
686@var{tptr} to current values.  The elements of the structure afterwards
687contain the values the timer implementation in the kernel assumes.  They
688might or might not be correct.  If they are not, an @code{ntp_adjtime}
689call is necessary.
690
691The return value is @code{0} on success and other values on failure.  The
692following @code{errno} error conditions are defined for this function:
693
694@vtable @code
695@item TIME_ERROR
696The precision clock model is not properly set up at the moment, thus the
697clock must be considered unsynchronized, and the values should be
698treated with care.
699@end vtable
700@end deftypefun
701
702@tindex struct timex
703@deftp {Data Type} {struct timex}
704This structure is used to control and monitor the system clock.  It
705contains the following members:
706@table @code
707@item unsigned int modes
708This variable controls whether and which values are set.  Several
709symbolic constants have to be combined with @emph{binary or} to specify
710the effective mode.  These constants start with @code{MOD_}.
711
712@item long int offset
713This value indicates the current offset of the system clock from the true
714calendar time.  The value is given in microseconds.  If bit
715@code{MOD_OFFSET} is set in @code{modes}, the offset (and possibly other
716dependent values) can be set.  The offset's absolute value must not
717exceed @code{MAXPHASE}.
718
719
720@item long int frequency
721This value indicates the difference in frequency between the true
722calendar time and the system clock.  The value is expressed as scaled
723PPM (parts per million, 0.0001%).  The scaling is @code{1 <<
724SHIFT_USEC}.  The value can be set with bit @code{MOD_FREQUENCY}, but
725the absolute value must not exceed @code{MAXFREQ}.
726
727@item long int maxerror
728This is the maximum error, measured in microseconds.  A new value can be
729set using bit @code{MOD_MAXERROR}.  Unless updated via
730@code{ntp_adjtime} periodically, this value will increase steadily
731and reach some platform-specific maximum value.
732
733@item long int esterror
734This is the estimated error, measured in microseconds.  This value can
735be set using bit @code{MOD_ESTERROR}.
736
737@item int status
738This variable reflects the various states of the clock machinery.  There
739are symbolic constants for the significant bits, starting with
740@code{STA_}.  Some of these flags can be updated using the
741@code{MOD_STATUS} bit.
742
743@item long int constant
744This value represents the bandwidth or stiffness of the PLL (phase
745locked loop) implemented in the kernel.  The value can be changed using
746bit @code{MOD_TIMECONST}.
747
748@item long int precision
749This value represents the accuracy or the maximum error when reading the
750system clock.  The value is expressed in microseconds.
751
752@item long int tolerance
753This value represents the maximum frequency error of the system clock in
754scaled PPM.  This value is used to increase the @code{maxerror} every
755second.
756
757@item struct timeval time
758The current calendar time.
759
760@item long int tick
761The elapsed time between clock ticks in microseconds.  A clock tick is a
762periodic timer interrupt on which the system clock is based.
763
764@item long int ppsfreq
765This is the first of a few optional variables that are present only if
766the system clock can use a PPS (pulse per second) signal to discipline
767the system clock.  The value is expressed in scaled PPM and it denotes
768the difference in frequency between the system clock and the PPS signal.
769
770@item long int jitter
771This value expresses a median filtered average of the PPS signal's
772dispersion in microseconds.
773
774@item int shift
775This value is a binary exponent for the duration of the PPS calibration
776interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
777
778@item long int stabil
779This value represents the median filtered dispersion of the PPS
780frequency in scaled PPM.
781
782@item long int jitcnt
783This counter represents the number of pulses where the jitter exceeded
784the allowed maximum @code{MAXTIME}.
785
786@item long int calcnt
787This counter reflects the number of successful calibration intervals.
788
789@item long int errcnt
790This counter represents the number of calibration errors (caused by
791large offsets or jitter).
792
793@item long int stbcnt
794This counter denotes the number of calibrations where the stability
795exceeded the threshold.
796@end table
797@end deftp
798
799@deftypefun int ntp_adjtime (struct timex *@var{tptr})
800@standards{GNU, sys/timex.h}
801@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
802@c Alias to adjtimex syscall.
803The @code{ntp_adjtime} function sets the structure specified by
804@var{tptr} to current values.
805
806In addition, @code{ntp_adjtime} updates some settings to match what
807you pass to it in @code{*@var{tptr}}.  Use the @code{modes} element of
808@code{*@var{tptr}} to select what settings to update.  You can set
809@code{offset}, @code{freq}, @code{maxerror}, @code{esterror},
810@code{status}, @code{constant}, and @code{tick}.
811
812@code{modes} = zero means set nothing.
813
814Only the superuser can update settings.
815
816@c On Linux, ntp_adjtime() also does the adjtime() function if you set
817@c modes = ADJ_OFFSET_SINGLESHOT (in fact, that is how GNU libc implements
818@c adjtime()).  But this should be considered an internal function because
819@c it's so inconsistent with the rest of what ntp_adjtime() does and is
820@c forced in an ugly way into the struct timex.  So we don't document it
821@c and instead document adjtime() as the way to achieve the function.
822
823The return value is @code{0} on success and other values on failure.  The
824following @code{errno} error conditions are defined for this function:
825
826@table @code
827@item TIME_ERROR
828The high accuracy clock model is not properly set up at the moment, thus the
829clock must be considered unsynchronized, and the values should be
830treated with care.  Another reason could be that the specified new values
831are not allowed.
832
833@item EPERM
834The process specified a settings update, but is not superuser.
835
836@end table
837
838For more details see RFC1305 (Network Time Protocol, Version 3) and
839related documents.
840
841@strong{Portability note:} Early versions of @theglibc{} did not
842have this function, but did have the synonymous @code{adjtimex}.
843@end deftypefun
844
845
846@c On Linux, GNU libc implements adjtime() as a call to adjtimex().
847@deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
848@standards{BSD, sys/time.h}
849@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
850@c On hurd and mach, call host_adjust_time with a privileged port.  On
851@c Linux, it's implemented in terms of adjtimex.  On other unixen, it's
852@c a syscall.
853This simpler version of @code{ntp_adjtime} speeds up or slows down the
854system clock for a short time, in order to correct it by a small
855amount.  This avoids a discontinuous change in the calendar time
856reported by the @code{CLOCK_REALTIME} clock, at the price of having to
857wait longer for the time to become correct.
858
859The @var{delta} argument specifies a relative adjustment to be made to
860the clock time.  If negative, the system clock is slowed down for a
861while until it has lost this much elapsed time.  If positive, the system
862clock is speeded up for a while.
863
864If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
865function returns information about any previous time adjustment that
866has not yet completed.
867
868The return value is @code{0} on success and @code{-1} on failure.  The
869following @code{errno} error condition is defined for this function:
870
871@table @code
872@item EPERM
873This process does not have the privileges required to adjust the
874@code{CLOCK_REALTIME} clock.
875@end table
876@end deftypefun
877
878For compatibility, @theglibc{} also provides several older functions
879for controlling the system time.  New programs should prefer to use
880the functions above.
881
882@deftypefun int stime (const time_t *@var{newtime})
883@standards{SVID, time.h}
884@standards{XPG, time.h}
885@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
886Change the @code{CLOCK_REALTIME} calendar time to be the simple
887calendar time in @code{*@var{newtime}}.  Calling this function is
888exactly the same as calling @w{@samp{clock_settime (CLOCK_REALTIME)}},
889except that the new time can only be set to a precision of one second.
890
891This function is no longer available on @gnusystems{}, but it may be
892the @emph{only} way to set the time on very old Unix systems, so we
893continue to document it.  If it is available, it is declared in
894@file{time.h}.
895
896The return value is @code{0} on success and @code{-1} on failure.  The
897following @code{errno} error condition is defined for this function:
898
899@table @code
900@item EPERM
901This process does not have the privileges required to adjust the
902@code{CLOCK_REALTIME} clock.
903@end table
904@end deftypefun
905
906@deftypefun int adjtimex (struct timex *@var{timex})
907@standards{GNU, sys/timex.h}
908@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
909@code{adjtimex} is an older name for @code{ntp_adjtime}.
910This function is only available on @gnulinuxsystems{}.
911It is declared in @file{sys/timex.h}.
912@end deftypefun
913
914@deftypefun int settimeofday (const struct timeval *@var{tp}, const void *@var{tzp})
915@standards{BSD, sys/time.h}
916@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
917Change the @code{CLOCK_REALTIME} calendar time to be the simple
918calendar time in @code{*@var{newtime}}.  This function is declared in
919@file{sys/time.h}.
920
921When @var{tzp} is a null pointer, calling this function is exactly the
922same as calling @w{@samp{clock_settime (CLOCK_REALTIME)}}, except that
923the new time can only be set to a precision of one microsecond.
924
925When @var{tzp} is not a null pointer, the data it points to @emph{may}
926be used to set a system-wide idea of the current timezone.  This
927feature is obsolete and not supported on @gnusystems{}.  Instead, use
928the facilities described in @ref{Time Zone Functions} and in
929@ref{Broken-down Time} for working with time zones.
930
931The return value is @code{0} on success and @code{-1} on failure.  The
932following @code{errno} error conditions are defined for this function:
933
934@table @code
935@item EPERM
936This process does not have the privileges required to set the
937@code{CLOCK_REALTIME} clock.
938
939@item EINVAL
940Neither @var{tp} nor @var{tzp} is a null pointer.  (For historical
941reasons, it is not possible to set the current time and the current
942time zone in the same call.)
943
944@item ENOSYS
945The operating system does not support setting time zone information, and
946@var{tzp} is not a null pointer.
947@end table
948@end deftypefun
949
950@node Broken-down Time
951@subsection Broken-down Time
952@cindex broken-down time
953@cindex calendar time and broken-down time
954
955Simple calendar times represent absolute times as elapsed times since
956an epoch.  This is convenient for computation, but has no relation to
957the way people normally think of calendar time.  By contrast,
958@dfn{broken-down time} is a binary representation of calendar time
959separated into year, month, day, and so on.  Broken-down time values
960are not useful for calculations, but they are useful for printing
961human readable time information.
962
963A broken-down time value is always relative to a choice of time
964zone, and it also indicates which time zone that is.
965
966The symbols in this section are declared in the header file @file{time.h}.
967
968@deftp {Data Type} {struct tm}
969@standards{ISO, time.h}
970This is the data type used to represent a broken-down time.  The structure
971contains at least the following members, which can appear in any order.
972
973@table @code
974@item int tm_sec
975This is the number of full seconds since the top of the minute (normally
976in the range @code{0} through @code{59}, but the actual upper limit is
977@code{60}, to allow for leap seconds if leap second support is
978available).
979@cindex leap second
980
981@item int tm_min
982This is the number of full minutes since the top of the hour (in the
983range @code{0} through @code{59}).
984
985@item int tm_hour
986This is the number of full hours past midnight (in the range @code{0} through
987@code{23}).
988
989@item int tm_mday
990This is the ordinal day of the month (in the range @code{1} through @code{31}).
991Watch out for this one!  As the only ordinal number in the structure, it is
992inconsistent with the rest of the structure.
993
994@item int tm_mon
995This is the number of full calendar months since the beginning of the
996year (in the range @code{0} through @code{11}).  Watch out for this one!
997People usually use ordinal numbers for month-of-year (where January = 1).
998
999@item int tm_year
1000This is the number of full calendar years since 1900.
1001
1002@item int tm_wday
1003This is the number of full days since Sunday (in the range @code{0} through
1004@code{6}).
1005
1006@item int tm_yday
1007This is the number of full days since the beginning of the year (in the
1008range @code{0} through @code{365}).
1009
1010@item int tm_isdst
1011@cindex Daylight Saving Time
1012@cindex summer time
1013This is a flag that indicates whether Daylight Saving Time is (or was, or
1014will be) in effect at the time described.  The value is positive if
1015Daylight Saving Time is in effect, zero if it is not, and negative if the
1016information is not available.
1017
1018@item long int tm_gmtoff
1019This field describes the time zone that was used to compute this
1020broken-down time value, including any adjustment for daylight saving; it
1021is the number of seconds that you must add to UTC to get local time.
1022You can also think of this as the number of seconds east of UTC.  For
1023example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
1024The @code{tm_gmtoff} field is derived from BSD and is a GNU library
1025extension; it is not visible in a strict @w{ISO C} environment.
1026
1027@item const char *tm_zone
1028This field is the name for the time zone that was used to compute this
1029broken-down time value.  Like @code{tm_gmtoff}, this field is a BSD and
1030GNU extension, and is not visible in a strict @w{ISO C} environment.
1031@end table
1032@end deftp
1033
1034
1035@deftypefun {struct tm *} localtime (const time_t *@var{time})
1036@standards{ISO, time.h}
1037@safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1038@c Calls tz_convert with a static buffer.
1039@c localtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1040@c  tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1041The @code{localtime} function converts the simple time pointed to by
1042@var{time} to broken-down time representation, expressed relative to the
1043user's specified time zone.
1044
1045The return value is a pointer to a static broken-down time structure, which
1046might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
1047or @code{localtime}.  (But no other library function overwrites the contents
1048of this object.)
1049
1050The return value is the null pointer if @var{time} cannot be represented
1051as a broken-down time; typically this is because the year cannot fit into
1052an @code{int}.
1053
1054Calling @code{localtime} also sets the current time zone as if
1055@code{tzset} were called.  @xref{Time Zone Functions}.
1056@end deftypefun
1057
1058Using the @code{localtime} function is a big problem in multi-threaded
1059programs.  The result is returned in a static buffer and this is used in
1060all threads.  POSIX.1c introduced a variant of this function.
1061
1062@deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
1063@standards{POSIX.1c, time.h}
1064@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1065@c localtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1066@c  tz_convert(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1067@c   libc_lock_lock dup @asulock @aculock
1068@c   tzset_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1069@c     always called with tzset_lock held
1070@c     sets static is_initialized before initialization;
1071@c     reads and sets old_tz; sets tz_rules.
1072@c     some of the issues only apply on the first call.
1073@c     subsequent calls only trigger these when called by localtime;
1074@c     otherwise, they're ok.
1075@c    getenv dup @mtsenv
1076@c    strcmp dup ok
1077@c    strdup @ascuheap
1078@c    tzfile_read @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1079@c     memcmp dup ok
1080@c     strstr dup ok
1081@c     getenv dup @mtsenv
1082@c     asprintf dup @mtslocale @ascuheap @acsmem
1083@c     stat64 dup ok
1084@c     fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
1085@c     fileno dup ok
1086@c     fstat64 dup ok
1087@c     fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
1088@c     free dup @ascuheap @acsmem
1089@c     fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
1090@c     fread_unlocked dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1091@c     memcpy dup ok
1092@c     decode ok
1093@c      bswap_32 dup ok
1094@c     fseek dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1095@c     ftello dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1096@c     malloc dup @ascuheap @acsmem
1097@c     decode64 ok
1098@c      bswap_64 dup ok
1099@c     getc_unlocked ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1100@c     tzstring dup @ascuheap @acsmem
1101@c     compute_tzname_max dup ok [guarded by tzset_lock]
1102@c    memset dup ok
1103@c    update_vars ok [guarded by tzset_lock]
1104@c      sets daylight, timezone, tzname and tzname_cur_max;
1105@c      called only with tzset_lock held, unless tzset_parse_tz
1106@c      (internal, but not static) gets called by users; given the its
1107@c      double-underscore-prefixed name, this interface violation could
1108@c      be regarded as undefined behavior.
1109@c     strlen ok
1110@c    tzset_parse_tz @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1111@c     sscanf dup @mtslocale @ascuheap @acsmem
1112@c     isalnum dup @mtsenv
1113@c     tzstring @ascuheap @acsmem
1114@c       reads and changes tzstring_list without synchronization, but
1115@c       only called with tzset_lock held (save for interface violations)
1116@c      strlen dup ok
1117@c      malloc dup @ascuheap @acsmem
1118@c      strcpy dup ok
1119@c     isdigit dup @mtslocale
1120@c     compute_offset ok
1121@c     tzfile_default @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1122@c       sets tzname, timezone, types, zone_names, rule_*off, etc; no guards
1123@c      strlen dup ok
1124@c      tzfile_read dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1125@c      mempcpy dup ok
1126@c      compute_tzname_max ok [if guarded by tzset_lock]
1127@c        iterates over zone_names; no guards
1128@c     free dup @ascuheap @acsmem
1129@c     strtoul dup @mtslocale
1130@c     update_vars dup ok
1131@c   tzfile_compute(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1132@c     sets tzname; no guards.  with !use_localtime, as in gmtime, it's ok
1133@c    tzstring dup @acsuheap @acsmem
1134@c    tzset_parse_tz dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1135@c    offtime dup ok
1136@c    tz_compute dup ok
1137@c    strcmp dup ok
1138@c   offtime ok
1139@c    isleap dup ok
1140@c   tz_compute ok
1141@c    compute_change ok
1142@c     isleap ok
1143@c   libc_lock_unlock dup @aculock
1144
1145The @code{localtime_r} function works just like the @code{localtime}
1146function.  It takes a pointer to a variable containing a simple time
1147and converts it to the broken-down time format.
1148
1149But the result is not placed in a static buffer.  Instead it is placed
1150in the object of type @code{struct tm} to which the parameter
1151@var{resultp} points.
1152
1153If the conversion is successful the function returns a pointer to the
1154object the result was written into, i.e., it returns @var{resultp}.
1155@end deftypefun
1156
1157
1158@deftypefun {struct tm *} gmtime (const time_t *@var{time})
1159@standards{ISO, time.h}
1160@safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1161@c gmtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1162@c  tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1163This function is similar to @code{localtime}, except that the broken-down
1164time is expressed as Coordinated Universal Time (UTC) (formerly called
1165Greenwich Mean Time (GMT)) rather than relative to a local time zone.
1166
1167@end deftypefun
1168
1169As for the @code{localtime} function we have the problem that the result
1170is placed in a static variable.  POSIX.1c also provides a replacement for
1171@code{gmtime}.
1172
1173@deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
1174@standards{POSIX.1c, time.h}
1175@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1176@c You'd think tz_convert could avoid some safety issues with
1177@c !use_localtime, but no such luck: tzset_internal will always bring
1178@c about all possible AS and AC problems when it's first called.
1179@c Calling any of localtime,gmtime_r once would run the initialization
1180@c and avoid the heap, mem and fd issues in gmtime* in subsequent calls,
1181@c but the unsafe locking would remain.
1182@c gmtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1183@c  tz_convert(gmtime_r) dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1184This function is similar to @code{localtime_r}, except that it converts
1185just like @code{gmtime} the given time as Coordinated Universal Time.
1186
1187If the conversion is successful the function returns a pointer to the
1188object the result was written into, i.e., it returns @var{resultp}.
1189@end deftypefun
1190
1191
1192@deftypefun time_t mktime (struct tm *@var{brokentime})
1193@standards{ISO, time.h}
1194@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1195@c mktime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1196@c   passes a static localtime_offset to mktime_internal; it is read
1197@c   once, used as an initial guess, and updated at the end, but not
1198@c   used except as a guess for subsequent calls, so it should be safe.
1199@c   Even though a compiler might delay the load and perform it multiple
1200@c   times (bug 16346), there are at least two unconditional uses of the
1201@c   auto variable in which the first load is stored, separated by a
1202@c   call to an external function, and a conditional change of the
1203@c   variable before the external call, so refraining from allocating a
1204@c   local variable at the first load would be a very bad optimization.
1205@c  tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1206@c  mktime_internal(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1207@c   ydhms_diff ok
1208@c   ranged_convert(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1209@c    *convert = localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1210@c    time_t_avg dup ok
1211@c   guess_time_tm dup ok
1212@c    ydhms_diff dup ok
1213@c    time_t_add_ok ok
1214@c     time_t_avg ok
1215@c   isdst_differ ok
1216@c   time_t_int_add_ok ok
1217The @code{mktime} function converts a broken-down time structure to a
1218simple time representation.  It also normalizes the contents of the
1219broken-down time structure, and fills in some components based on the
1220values of the others.
1221
1222The @code{mktime} function ignores the specified contents of the
1223@code{tm_wday}, @code{tm_yday}, @code{tm_gmtoff}, and @code{tm_zone}
1224members of the broken-down time
1225structure.  It uses the values of the other components to determine the
1226calendar time; it's permissible for these components to have
1227unnormalized values outside their normal ranges.  The last thing that
1228@code{mktime} does is adjust the components of the @var{brokentime}
1229structure, including the members that were initially ignored.
1230
1231If the specified broken-down time cannot be represented as a simple time,
1232@code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
1233the contents of @var{brokentime}.
1234
1235Calling @code{mktime} also sets the current time zone as if
1236@code{tzset} were called; @code{mktime} uses this information instead
1237of @var{brokentime}'s initial @code{tm_gmtoff} and @code{tm_zone}
1238members.  @xref{Time Zone Functions}.
1239@end deftypefun
1240
1241@deftypefun time_t timelocal (struct tm *@var{brokentime})
1242@standards{???, time.h}
1243@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1244@c Alias to mktime.
1245
1246@code{timelocal} is functionally identical to @code{mktime}, but more
1247mnemonically named.  Note that it is the inverse of the @code{localtime}
1248function.
1249
1250@strong{Portability note:}  @code{mktime} is essentially universally
1251available.  @code{timelocal} is rather rare.
1252
1253@end deftypefun
1254
1255@deftypefun time_t timegm (struct tm *@var{brokentime})
1256@standards{???, time.h}
1257@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1258@c timegm @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1259@c   gmtime_offset triggers the same caveats as localtime_offset in mktime.
1260@c   although gmtime_r, as called by mktime, might save some issues,
1261@c   tzset calls tzset_internal with always, which forces
1262@c   reinitialization, so all issues may arise.
1263@c  tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1264@c  mktime_internal(gmtime_r) @asulock @aculock
1265@c ..gmtime_r @asulock @aculock
1266@c    ... dup ok
1267@c    tz_convert(!use_localtime) @asulock @aculock
1268@c     ... dup @asulock @aculock
1269@c     tzfile_compute(!use_localtime) ok
1270
1271@code{timegm} is functionally identical to @code{mktime} except it
1272always takes the input values to be Coordinated Universal Time (UTC)
1273regardless of any local time zone setting.
1274
1275Note that @code{timegm} is the inverse of @code{gmtime}.
1276
1277@strong{Portability note:}  @code{mktime} is essentially universally
1278available.  @code{timegm} is rather rare.  For the most portable
1279conversion from a UTC broken-down time to a simple time, set
1280the @code{TZ} environment variable to UTC, call @code{mktime}, then set
1281@code{TZ} back.
1282
1283@end deftypefun
1284
1285
1286
1287@node Formatting Calendar Time
1288@subsection Formatting Calendar Time
1289
1290The functions described in this section format calendar time values as
1291strings.  These functions are declared in the header file @file{time.h}.
1292@pindex time.h
1293
1294@deftypefun {char *} asctime (const struct tm *@var{brokentime})
1295@standards{ISO, time.h}
1296@safety{@prelim{}@mtunsafe{@mtasurace{:asctime} @mtslocale{}}@asunsafe{}@acsafe{}}
1297@c asctime @mtasurace:asctime @mtslocale
1298@c   Uses a static buffer.
1299@c  asctime_internal @mtslocale
1300@c   snprintf dup @mtslocale [no @acsuheap @acsmem]
1301@c   ab_day_name @mtslocale
1302@c   ab_month_name @mtslocale
1303The @code{asctime} function converts the broken-down time value that
1304@var{brokentime} points to into a string in a standard format:
1305
1306@smallexample
1307"Tue May 21 13:46:22 1991\n"
1308@end smallexample
1309
1310The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
1311@samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
1312
1313The abbreviations for the months are: @samp{Jan}, @samp{Feb},
1314@samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
1315@samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
1316
1317The return value points to a statically allocated string, which might be
1318overwritten by subsequent calls to @code{asctime} or @code{ctime}.
1319(But no other library function overwrites the contents of this
1320string.)
1321@end deftypefun
1322
1323@deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
1324@standards{POSIX.1c, time.h}
1325@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1326@c asctime_r @mtslocale
1327@c  asctime_internal dup @mtslocale
1328This function is similar to @code{asctime} but instead of placing the
1329result in a static buffer it writes the string in the buffer pointed to
1330by the parameter @var{buffer}.  This buffer should have room
1331for at least 26 bytes, including the terminating null.
1332
1333If no error occurred the function returns a pointer to the string the
1334result was written into, i.e., it returns @var{buffer}.  Otherwise
1335it returns @code{NULL}.
1336@end deftypefun
1337
1338
1339@deftypefun {char *} ctime (const time_t *@var{time})
1340@standards{ISO, time.h}
1341@safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtasurace{:asctime} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1342@c ctime @mtasurace:tmbuf @mtasurace:asctime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1343@c  localtime dup @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1344@c  asctime dup @mtasurace:asctime @mtslocale
1345The @code{ctime} function is similar to @code{asctime}, except that you
1346specify the calendar time argument as a @code{time_t} simple time value
1347rather than in broken-down local time format.  It is equivalent to
1348
1349@smallexample
1350asctime (localtime (@var{time}))
1351@end smallexample
1352
1353Calling @code{ctime} also sets the current time zone as if
1354@code{tzset} were called.  @xref{Time Zone Functions}.
1355@end deftypefun
1356
1357@deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
1358@standards{POSIX.1c, time.h}
1359@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1360@c ctime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1361@c  localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1362@c  asctime_r dup @mtslocale
1363This function is similar to @code{ctime}, but places the result in the
1364string pointed to by @var{buffer}.  It is equivalent to (written using
1365gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
1366
1367@smallexample
1368(@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
1369@end smallexample
1370
1371If no error occurred the function returns a pointer to the string the
1372result was written into, i.e., it returns @var{buffer}.  Otherwise
1373it returns @code{NULL}.
1374@end deftypefun
1375
1376
1377@deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
1378@standards{ISO, time.h}
1379@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1380@c strftime @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1381@c  strftime_l @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1382@c   strftime_internal @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1383@c    add ok
1384@c     memset_zero dup ok
1385@c     memset_space dup ok
1386@c    strlen dup ok
1387@c    mbrlen @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd [no @mtasurace:mbstate/!ps]
1388@c    mbsinit dup ok
1389@c    cpy ok
1390@c     add dup ok
1391@c     memcpy_lowcase ok
1392@c      TOLOWER ok
1393@c       tolower_l ok
1394@c     memcpy_uppcase ok
1395@c      TOUPPER ok
1396@c       toupper_l ok
1397@c     MEMCPY ok
1398@c      memcpy dup ok
1399@c    ISDIGIT ok
1400@c    STRLEN ok
1401@c     strlen dup ok
1402@c    strftime_internal dup @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1403@c    TOUPPER dup ok
1404@c    nl_get_era_entry @ascuheap @asulock @acsmem @aculock
1405@c     nl_init_era_entries @ascuheap @asulock @acsmem @aculock
1406@c      libc_rwlock_wrlock dup @asulock @aculock
1407@c      malloc dup @ascuheap @acsmem
1408@c      memset dup ok
1409@c      free dup @ascuheap @acsmem
1410@c      realloc dup @ascuheap @acsmem
1411@c      memcpy dup ok
1412@c      strchr dup ok
1413@c      wcschr dup ok
1414@c      libc_rwlock_unlock dup @asulock @aculock
1415@c     ERA_DATE_CMP ok
1416@c    DO_NUMBER ok
1417@c    DO_NUMBER_SPACEPAD ok
1418@c    nl_get_alt_digit @ascuheap @asulock @acsmem @aculock
1419@c     libc_rwlock_wrlock dup @asulock @aculock
1420@c     nl_init_alt_digit @ascuheap @acsmem
1421@c      malloc dup @ascuheap @acsmem
1422@c      memset dup ok
1423@c      strchr dup ok
1424@c     libc_rwlock_unlock dup @aculock
1425@c    memset_space ok
1426@c     memset dup ok
1427@c    memset_zero ok
1428@c     memset dup ok
1429@c    mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1430@c    iso_week_days ok
1431@c    isleap ok
1432@c    tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1433@c    localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1434@c    gmtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1435@c    tm_diff ok
1436This function is similar to the @code{sprintf} function (@pxref{Formatted
1437Input}), but the conversion specifications that can appear in the format
1438template @var{template} are specialized for printing components of the date
1439and time @var{brokentime} according to the locale currently specified for
1440time conversion (@pxref{Locales}) and the current time zone
1441(@pxref{Time Zone Functions}).
1442
1443Ordinary characters appearing in the @var{template} are copied to the
1444output string @var{s}; this can include multibyte character sequences.
1445Conversion specifiers are introduced by a @samp{%} character, followed
1446by an optional flag which can be one of the following.  These flags
1447are all GNU extensions.  The first three affect only the output of
1448numbers:
1449
1450@table @code
1451@item _
1452The number is padded with spaces.
1453
1454@item -
1455The number is not padded at all.
1456
1457@item 0
1458The number is padded with zeros even if the format specifies padding
1459with spaces.
1460
1461@item ^
1462The output uses uppercase characters, but only if this is possible
1463(@pxref{Case Conversion}).
1464@end table
1465
1466The default action is to pad the number with zeros to keep it a constant
1467width.  Numbers that do not have a range indicated below are never
1468padded, since there is no natural width for them.
1469
1470Following the flag an optional specification of the width is possible.
1471This is specified in decimal notation.  If the natural size of the
1472output of the field has less than the specified number of characters,
1473the result is written right adjusted and space padded to the given
1474size.
1475
1476An optional modifier can follow the optional flag and width
1477specification.  The modifiers, which were first standardized by
1478POSIX.2-1992 and by @w{ISO C99}, are:
1479
1480@table @code
1481@item E
1482Use the locale's alternative representation for date and time.  This
1483modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
1484@code{%y} and @code{%Y} format specifiers.  In a Japanese locale, for
1485example, @code{%Ex} might yield a date format based on the Japanese
1486Emperors' reigns.
1487
1488@item O
1489With all format specifiers that produce numbers: use the locale's
1490alternative numeric symbols.
1491
1492With @code{%B}, @code{%b}, and @code{%h}: use the grammatical form for
1493month names that is appropriate when the month is named by itself,
1494rather than the form that is appropriate when the month is used as
1495part of a complete date.  The @code{%OB} and @code{%Ob} formats are a
1496C2X feature, specified in C2X to use the locale's `alternative' month
1497name; @theglibc{} extends this specification to say that the form used
1498in a complete date is the default and the form naming the month by
1499itself is the alternative.
1500@end table
1501
1502If the format supports the modifier but no alternative representation
1503is available, it is ignored.
1504
1505The conversion specifier ends with a format specifier taken from the
1506following list.  The whole @samp{%} sequence is replaced in the output
1507string as follows:
1508
1509@table @code
1510@item %a
1511The abbreviated weekday name according to the current locale.
1512
1513@item %A
1514The full weekday name according to the current locale.
1515
1516@item %b
1517The abbreviated month name according to the current locale, in the
1518grammatical form used when the month is part of a complete date.
1519As a C2X feature (with a more detailed specification in @theglibc{}),
1520the @code{O} modifier can be used (@code{%Ob}) to get the grammatical
1521form used when the month is named by itself.
1522
1523@item %B
1524The full month name according to the current locale, in the
1525grammatical form used when the month is part of a complete date.
1526As a C2X feature (with a more detailed specification in @theglibc{}),
1527the @code{O} modifier can be used (@code{%OB}) to get the grammatical
1528form used when the month is named by itself.
1529
1530Note that not all languages need two different forms of the month
1531names, so the text produced by @code{%B} and @code{%OB}, and by
1532@code{%b} and @code{%Ob}, may or may not be the same, depending on
1533the locale.
1534
1535@item %c
1536The preferred calendar time representation for the current locale.
1537
1538@item %C
1539The century of the year.  This is equivalent to the greatest integer not
1540greater than the year divided by 100.
1541
1542If the @code{E} modifier is specified (@code{%EC}), instead produces
1543the name of the period for the year (e.g.@: an era name) in the
1544locale's alternative calendar.
1545
1546This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1547
1548@item %d
1549The day of the month as a decimal number (range @code{01} through @code{31}).
1550
1551@item %D
1552The date using the format @code{%m/%d/%y}.
1553
1554This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1555
1556@item %e
1557The day of the month like with @code{%d}, but padded with spaces (range
1558@code{ 1} through @code{31}).
1559
1560This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1561
1562@item %F
1563The date using the format @code{%Y-%m-%d}.  This is the form specified
1564in the @w{ISO 8601} standard and is the preferred form for all uses.
1565
1566This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
1567
1568@item %g
1569The year corresponding to the ISO week number, but without the century
1570(range @code{00} through @code{99}).  This has the same format and value
1571as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
1572to the previous or next year, that year is used instead.
1573
1574This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
1575
1576@item %G
1577The year corresponding to the ISO week number.  This has the same format
1578and value as @code{%Y}, except that if the ISO week number (see
1579@code{%V}) belongs to the previous or next year, that year is used
1580instead.
1581
1582This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1583but was previously available as a GNU extension.
1584
1585@item %h
1586The abbreviated month name according to the current locale.  The action
1587is the same as for @code{%b}.
1588
1589This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1590
1591@item %H
1592The hour as a decimal number, using a 24-hour clock (range @code{00} through
1593@code{23}).
1594
1595@item %I
1596The hour as a decimal number, using a 12-hour clock (range @code{01} through
1597@code{12}).
1598
1599@item %j
1600The day of the year as a decimal number (range @code{001} through @code{366}).
1601
1602@item %k
1603The hour as a decimal number, using a 24-hour clock like @code{%H}, but
1604padded with spaces (range @code{ 0} through @code{23}).
1605
1606This format is a GNU extension.
1607
1608@item %l
1609The hour as a decimal number, using a 12-hour clock like @code{%I}, but
1610padded with spaces (range @code{ 1} through @code{12}).
1611
1612This format is a GNU extension.
1613
1614@item %m
1615The month as a decimal number (range @code{01} through @code{12}).
1616
1617@item %M
1618The minute as a decimal number (range @code{00} through @code{59}).
1619
1620@item %n
1621A single @samp{\n} (newline) character.
1622
1623This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1624
1625@item %p
1626Either @samp{AM} or @samp{PM}, according to the given time value; or the
1627corresponding strings for the current locale.  Noon is treated as
1628@samp{PM} and midnight as @samp{AM}.  In most locales
1629@samp{AM}/@samp{PM} format is not supported, in such cases @code{"%p"}
1630yields an empty string.
1631
1632@ignore
1633We currently have a problem with makeinfo.  Write @samp{AM} and @samp{am}
1634both results in `am'.  I.e., the difference in case is not visible anymore.
1635@end ignore
1636@item %P
1637Either @samp{am} or @samp{pm}, according to the given time value; or the
1638corresponding strings for the current locale, printed in lowercase
1639characters.  Noon is treated as @samp{pm} and midnight as @samp{am}.  In
1640most locales @samp{AM}/@samp{PM} format is not supported, in such cases
1641@code{"%P"} yields an empty string.
1642
1643This format is a GNU extension.
1644
1645@item %r
1646The complete calendar time using the AM/PM format of the current locale.
1647
1648This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1649In the POSIX locale, this format is equivalent to @code{%I:%M:%S %p}.
1650
1651@item %R
1652The hour and minute in decimal numbers using the format @code{%H:%M}.
1653
1654This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1655but was previously available as a GNU extension.
1656
1657@item %s
1658The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1659Leap seconds are not counted unless leap second support is available.
1660
1661This format is a GNU extension.
1662
1663@item %S
1664The seconds as a decimal number (range @code{00} through @code{60}).
1665
1666@item %t
1667A single @samp{\t} (tabulator) character.
1668
1669This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1670
1671@item %T
1672The time of day using decimal numbers using the format @code{%H:%M:%S}.
1673
1674This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1675
1676@item %u
1677The day of the week as a decimal number (range @code{1} through
1678@code{7}), Monday being @code{1}.
1679
1680This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1681
1682@item %U
1683The week number of the current year as a decimal number (range @code{00}
1684through @code{53}), starting with the first Sunday as the first day of
1685the first week.  Days preceding the first Sunday in the year are
1686considered to be in week @code{00}.
1687
1688@item %V
1689The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
1690through @code{53}).  ISO weeks start with Monday and end with Sunday.
1691Week @code{01} of a year is the first week which has the majority of its
1692days in that year; this is equivalent to the week containing the year's
1693first Thursday, and it is also equivalent to the week containing January
16944.  Week @code{01} of a year can contain days from the previous year.
1695The week before week @code{01} of a year is the last week (@code{52} or
1696@code{53}) of the previous year even if it contains days from the new
1697year.
1698
1699This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1700
1701@item %w
1702The day of the week as a decimal number (range @code{0} through
1703@code{6}), Sunday being @code{0}.
1704
1705@item %W
1706The week number of the current year as a decimal number (range @code{00}
1707through @code{53}), starting with the first Monday as the first day of
1708the first week.  All days preceding the first Monday in the year are
1709considered to be in week @code{00}.
1710
1711@item %x
1712The preferred date representation for the current locale.
1713
1714@item %X
1715The preferred time of day representation for the current locale.
1716
1717@item %y
1718The year without a century as a decimal number (range @code{00} through
1719@code{99}).  This is equivalent to the year modulo 100.
1720
1721If the @code{E} modifier is specified (@code{%Ey}), instead produces
1722the year number according to a locale-specific alternative calendar.
1723Unlike @code{%y}, the number is @emph{not} reduced modulo 100.
1724However, by default it is zero-padded to a minimum of two digits (this
1725can be overridden by an explicit field width or by the @code{_} and
1726@code{-} flags).
1727
1728@item %Y
1729The year as a decimal number, using the Gregorian calendar.  Years
1730before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
1731
1732If the @code{E} modifier is specified (@code{%EY}), instead produces a
1733complete representation of the year according to the locale's
1734alternative calendar.  Generally this will be some combination of the
1735information produced by @code{%EC} and @code{%Ey}.  As a GNU
1736extension, the formatting flags @code{_} or @code{-} may be used with
1737this conversion specifier; they affect how the year number is printed.
1738
1739@item %z
1740@w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
1741@code{-0600} or @code{+0100}), or nothing if no time zone is
1742determinable.
1743
1744This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1745but was previously available as a GNU extension.
1746
1747In the POSIX locale, a full @w{RFC 822} timestamp is generated by the format
1748@w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
1749@w{@samp{"%a, %d %b %Y %T %z"}}).
1750
1751@item %Z
1752The time zone abbreviation (empty if the time zone can't be determined).
1753
1754@item %%
1755A literal @samp{%} character.
1756@end table
1757
1758The @var{size} parameter can be used to specify the maximum number of
1759characters to be stored in the array @var{s}, including the terminating
1760null character.  If the formatted time requires more than @var{size}
1761characters, @code{strftime} returns zero and the contents of the array
1762@var{s} are undefined.  Otherwise the return value indicates the
1763number of characters placed in the array @var{s}, not including the
1764terminating null character.
1765
1766@emph{Warning:} This convention for the return value which is prescribed
1767in @w{ISO C} can lead to problems in some situations.  For certain
1768format strings and certain locales the output really can be the empty
1769string and this cannot be discovered by testing the return value only.
1770E.g., in most locales the AM/PM time format is not supported (most of
1771the world uses the 24 hour time representation).  In such locales
1772@code{"%p"} will return the empty string, i.e., the return value is
1773zero.  To detect situations like this something similar to the following
1774code should be used:
1775
1776@smallexample
1777buf[0] = '\1';
1778len = strftime (buf, bufsize, format, tp);
1779if (len == 0 && buf[0] != '\0')
1780  @{
1781    /* Something went wrong in the strftime call.  */
1782    @dots{}
1783  @}
1784@end smallexample
1785
1786If @var{s} is a null pointer, @code{strftime} does not actually write
1787anything, but instead returns the number of characters it would have written.
1788
1789Calling @code{strftime} also sets the current time zone as if
1790@code{tzset} were called; @code{strftime} uses this information
1791instead of @var{brokentime}'s @code{tm_gmtoff} and @code{tm_zone}
1792members.  @xref{Time Zone Functions}.
1793
1794For an example of @code{strftime}, see @ref{Time Functions Example}.
1795@end deftypefun
1796
1797@deftypefun size_t wcsftime (wchar_t *@var{s}, size_t @var{size}, const wchar_t *@var{template}, const struct tm *@var{brokentime})
1798@standards{ISO/Amend1, time.h}
1799@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1800@c wcsftime @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1801@c  wcsftime_l @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1802@c   wcsftime_internal @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1803@c    add ok
1804@c     memset_zero dup ok
1805@c     memset_space dup ok
1806@c    wcslen dup ok
1807@c    cpy ok
1808@c     add dup ok
1809@c     memcpy_lowcase ok
1810@c      TOLOWER ok
1811@c       towlower_l dup ok
1812@c     memcpy_uppcase ok
1813@c      TOUPPER ok
1814@c       towupper_l dup ok
1815@c     MEMCPY ok
1816@c      wmemcpy dup ok
1817@c    widen @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1818@c     memset dup ok
1819@c     mbsrtowcs_l @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd [no @mtasurace:mbstate/!ps]
1820@c    ISDIGIT ok
1821@c    STRLEN ok
1822@c     wcslen dup ok
1823@c    wcsftime_internal dup @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1824@c    TOUPPER dup ok
1825@c    nl_get_era_entry dup @ascuheap @asulock @acsmem @aculock
1826@c    DO_NUMBER ok
1827@c    DO_NUMBER_SPACEPAD ok
1828@c    nl_get_walt_digit dup @ascuheap @asulock @acsmem @aculock
1829@c     libc_rwlock_wrlock dup @asulock @aculock
1830@c     nl_init_alt_digit dup @ascuheap @acsmem
1831@c     malloc dup @ascuheap @acsmem
1832@c     memset dup ok
1833@c     wcschr dup ok
1834@c     libc_rwlock_unlock dup @aculock
1835@c    memset_space ok
1836@c     wmemset dup ok
1837@c    memset_zero ok
1838@c     wmemset dup ok
1839@c    mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1840@c    iso_week_days ok
1841@c    isleap ok
1842@c    tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1843@c    localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1844@c    gmtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1845@c    tm_diff ok
1846The @code{wcsftime} function is equivalent to the @code{strftime}
1847function with the difference that it operates on wide character
1848strings.  The buffer where the result is stored, pointed to by @var{s},
1849must be an array of wide characters.  The parameter @var{size} which
1850specifies the size of the output buffer gives the number of wide
1851characters, not the number of bytes.
1852
1853Also the format string @var{template} is a wide character string.  Since
1854all characters needed to specify the format string are in the basic
1855character set it is portably possible to write format strings in the C
1856source code using the @code{L"@dots{}"} notation.  The parameter
1857@var{brokentime} has the same meaning as in the @code{strftime} call.
1858
1859The @code{wcsftime} function supports the same flags, modifiers, and
1860format specifiers as the @code{strftime} function.
1861
1862The return value of @code{wcsftime} is the number of wide characters
1863stored in @code{s}.  When more characters would have to be written than
1864can be placed in the buffer @var{s} the return value is zero, with the
1865same problems indicated in the @code{strftime} documentation.
1866@end deftypefun
1867
1868@node Parsing Date and Time
1869@subsection Convert textual time and date information back
1870
1871The @w{ISO C} standard does not specify any functions which can convert
1872the output of the @code{strftime} function back into a binary format.
1873This led to a variety of more-or-less successful implementations with
1874different interfaces over the years.  Then the Unix standard was
1875extended by the addition of two functions: @code{strptime} and
1876@code{getdate}.  Both have strange interfaces but at least they are
1877widely available.
1878
1879@menu
1880* Low-Level Time String Parsing::  Interpret string according to given format.
1881* General Time String Parsing::    User-friendly function to parse data and
1882                                    time strings.
1883@end menu
1884
1885@node Low-Level Time String Parsing
1886@subsubsection Interpret string according to given format
1887
1888The first function is rather low-level.  It is nevertheless frequently
1889used in software since it is better known.  Its interface and
1890implementation are heavily influenced by the @code{getdate} function,
1891which is defined and implemented in terms of calls to @code{strptime}.
1892
1893@deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1894@standards{XPG4, time.h}
1895@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1896@c strptime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1897@c  strptime_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1898@c   memset dup ok
1899@c   ISSPACE ok
1900@c    isspace_l dup ok
1901@c   match_char ok
1902@c   match_string ok
1903@c    strlen dup ok
1904@c    strncasecmp_l dup ok
1905@c   strcmp dup ok
1906@c   recursive @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1907@c    strptime_internal dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1908@c   get_number ok
1909@c    ISSPACE dup ok
1910@c   localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1911@c   nl_select_era_entry @ascuheap @asulock @acsmem @aculock
1912@c    nl_init_era_entries dup @ascuheap @asulock @acsmem @aculock
1913@c   get_alt_number dup @ascuheap @asulock @acsmem @aculock
1914@c    nl_parse_alt_digit dup @ascuheap @asulock @acsmem @aculock
1915@c     libc_rwlock_wrlock dup @asulock @aculock
1916@c     nl_init_alt_digit dup @ascuheap @acsmem
1917@c     libc_rwlock_unlock dup @aculock
1918@c    get_number dup ok
1919@c   day_of_the_week ok
1920@c   day_of_the_year ok
1921The @code{strptime} function parses the input string @var{s} according
1922to the format string @var{fmt} and stores its results in the
1923structure @var{tp}.
1924
1925The input string could be generated by a @code{strftime} call or
1926obtained any other way.  It does not need to be in a human-recognizable
1927format; e.g. a date passed as @code{"02:1999:9"} is acceptable, even
1928though it is ambiguous without context.  As long as the format string
1929@var{fmt} matches the input string the function will succeed.
1930
1931The user has to make sure, though, that the input can be parsed in a
1932unambiguous way.  The string @code{"1999112"} can be parsed using the
1933format @code{"%Y%m%d"} as 1999-1-12, 1999-11-2, or even 19991-1-2.  It
1934is necessary to add appropriate separators to reliably get results.
1935
1936The format string consists of the same components as the format string
1937of the @code{strftime} function.  The only difference is that the flags
1938@code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1939@comment Is this really the intention?  --drepper
1940Several of the distinct formats of @code{strftime} do the same work in
1941@code{strptime} since differences like case of the input do not matter.
1942For reasons of symmetry all formats are supported, though.
1943
1944The modifiers @code{E} and @code{O} are also allowed everywhere the
1945@code{strftime} function allows them.
1946
1947The formats are:
1948
1949@table @code
1950@item %a
1951@itemx %A
1952The weekday name according to the current locale, in abbreviated form or
1953the full name.
1954
1955@item %b
1956@itemx %B
1957@itemx %h
1958A month name according to the current locale.  All three specifiers
1959will recognize both abbreviated and full month names.  If the
1960locale provides two different grammatical forms of month names,
1961all three specifiers will recognize both forms.
1962
1963As a GNU extension, the @code{O} modifier can be used with these
1964specifiers; it has no effect, as both grammatical forms of month
1965names are recognized.
1966
1967@item %c
1968The date and time representation for the current locale.
1969
1970@item %Ec
1971Like @code{%c} but the locale's alternative date and time format is used.
1972
1973@item %C
1974The century of the year.
1975
1976It makes sense to use this format only if the format string also
1977contains the @code{%y} format.
1978
1979@item %EC
1980The locale's representation of the period.
1981
1982Unlike @code{%C} it sometimes makes sense to use this format since some
1983cultures represent years relative to the beginning of eras instead of
1984using the Gregorian years.
1985
1986@item %d
1987@item %e
1988The day of the month as a decimal number (range @code{1} through @code{31}).
1989Leading zeroes are permitted but not required.
1990
1991@item %Od
1992@itemx %Oe
1993Same as @code{%d} but using the locale's alternative numeric symbols.
1994
1995Leading zeroes are permitted but not required.
1996
1997@item %D
1998Equivalent to @code{%m/%d/%y}.
1999
2000@item %F
2001Equivalent to @code{%Y-%m-%d}, which is the @w{ISO 8601} date
2002format.
2003
2004This is a GNU extension following an @w{ISO C99} extension to
2005@code{strftime}.
2006
2007@item %g
2008The year corresponding to the ISO week number, but without the century
2009(range @code{00} through @code{99}).
2010
2011@emph{Note:} Currently, this is not fully implemented.  The format is
2012recognized, input is consumed but no field in @var{tm} is set.
2013
2014This format is a GNU extension following a GNU extension of @code{strftime}.
2015
2016@item %G
2017The year corresponding to the ISO week number.
2018
2019@emph{Note:} Currently, this is not fully implemented.  The format is
2020recognized, input is consumed but no field in @var{tm} is set.
2021
2022This format is a GNU extension following a GNU extension of @code{strftime}.
2023
2024@item %H
2025@itemx %k
2026The hour as a decimal number, using a 24-hour clock (range @code{00} through
2027@code{23}).
2028
2029@code{%k} is a GNU extension following a GNU extension of @code{strftime}.
2030
2031@item %OH
2032Same as @code{%H} but using the locale's alternative numeric symbols.
2033
2034@item %I
2035@itemx %l
2036The hour as a decimal number, using a 12-hour clock (range @code{01} through
2037@code{12}).
2038
2039@code{%l} is a GNU extension following a GNU extension of @code{strftime}.
2040
2041@item %OI
2042Same as @code{%I} but using the locale's alternative numeric symbols.
2043
2044@item %j
2045The day of the year as a decimal number (range @code{1} through @code{366}).
2046
2047Leading zeroes are permitted but not required.
2048
2049@item %m
2050The month as a decimal number (range @code{1} through @code{12}).
2051
2052Leading zeroes are permitted but not required.
2053
2054@item %Om
2055Same as @code{%m} but using the locale's alternative numeric symbols.
2056
2057@item %M
2058The minute as a decimal number (range @code{0} through @code{59}).
2059
2060Leading zeroes are permitted but not required.
2061
2062@item %OM
2063Same as @code{%M} but using the locale's alternative numeric symbols.
2064
2065@item %n
2066@itemx %t
2067Matches any white space.
2068
2069@item %p
2070@item %P
2071The locale-dependent equivalent to @samp{AM} or @samp{PM}.
2072
2073This format is not useful unless @code{%I} or @code{%l} is also used.
2074Another complication is that the locale might not define these values at
2075all and therefore the conversion fails.
2076
2077@code{%P} is a GNU extension following a GNU extension to @code{strftime}.
2078
2079@item %r
2080The complete time using the AM/PM format of the current locale.
2081
2082A complication is that the locale might not define this format at all
2083and therefore the conversion fails.
2084
2085@item %R
2086The hour and minute in decimal numbers using the format @code{%H:%M}.
2087
2088@code{%R} is a GNU extension following a GNU extension to @code{strftime}.
2089
2090@item %s
2091The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
2092Leap seconds are not counted unless leap second support is available.
2093
2094@code{%s} is a GNU extension following a GNU extension to @code{strftime}.
2095
2096@item %S
2097The seconds as a decimal number (range @code{0} through @code{60}).
2098
2099Leading zeroes are permitted but not required.
2100
2101@strong{NB:} The Unix specification says the upper bound on this value
2102is @code{61}, a result of a decision to allow double leap seconds.  You
2103will not see the value @code{61} because no minute has more than one
2104leap second, but the myth persists.
2105
2106@item %OS
2107Same as @code{%S} but using the locale's alternative numeric symbols.
2108
2109@item %T
2110Equivalent to the use of @code{%H:%M:%S} in this place.
2111
2112@item %u
2113The day of the week as a decimal number (range @code{1} through
2114@code{7}), Monday being @code{1}.
2115
2116Leading zeroes are permitted but not required.
2117
2118@emph{Note:} Currently, this is not fully implemented.  The format is
2119recognized, input is consumed but no field in @var{tm} is set.
2120
2121@item %U
2122The week number of the current year as a decimal number (range @code{0}
2123through @code{53}).
2124
2125Leading zeroes are permitted but not required.
2126
2127@item %OU
2128Same as @code{%U} but using the locale's alternative numeric symbols.
2129
2130@item %V
2131The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
2132through @code{53}).
2133
2134Leading zeroes are permitted but not required.
2135
2136@emph{Note:} Currently, this is not fully implemented.  The format is
2137recognized, input is consumed but no field in @var{tm} is set.
2138
2139@item %w
2140The day of the week as a decimal number (range @code{0} through
2141@code{6}), Sunday being @code{0}.
2142
2143Leading zeroes are permitted but not required.
2144
2145@emph{Note:} Currently, this is not fully implemented.  The format is
2146recognized, input is consumed but no field in @var{tm} is set.
2147
2148@item %Ow
2149Same as @code{%w} but using the locale's alternative numeric symbols.
2150
2151@item %W
2152The week number of the current year as a decimal number (range @code{0}
2153through @code{53}).
2154
2155Leading zeroes are permitted but not required.
2156
2157@emph{Note:} Currently, this is not fully implemented.  The format is
2158recognized, input is consumed but no field in @var{tm} is set.
2159
2160@item %OW
2161Same as @code{%W} but using the locale's alternative numeric symbols.
2162
2163@item %x
2164The date using the locale's date format.
2165
2166@item %Ex
2167Like @code{%x} but the locale's alternative data representation is used.
2168
2169@item %X
2170The time using the locale's time format.
2171
2172@item %EX
2173Like @code{%X} but the locale's alternative time representation is used.
2174
2175@item %y
2176The year without a century as a decimal number (range @code{0} through
2177@code{99}).
2178
2179Leading zeroes are permitted but not required.
2180
2181Note that it is questionable to use this format without
2182the @code{%C} format.  The @code{strptime} function does regard input
2183values in the range @math{68} to @math{99} as the years @math{1969} to
2184@math{1999} and the values @math{0} to @math{68} as the years
2185@math{2000} to @math{2068}.  But maybe this heuristic fails for some
2186input data.
2187
2188Therefore it is best to avoid @code{%y} completely and use @code{%Y}
2189instead.
2190
2191@item %Ey
2192The offset from @code{%EC} in the locale's alternative representation.
2193
2194@item %Oy
2195The offset of the year (from @code{%C}) using the locale's alternative
2196numeric symbols.
2197
2198@item %Y
2199The year as a decimal number, using the Gregorian calendar.
2200
2201@item %EY
2202The full alternative year representation.
2203
2204@item %z
2205The offset from GMT in @w{ISO 8601}/RFC822 format.
2206
2207@item %Z
2208The timezone name.
2209
2210@emph{Note:} Currently, this is not fully implemented.  The format is
2211recognized, input is consumed but no field in @var{tm} is set.
2212
2213@item %%
2214A literal @samp{%} character.
2215@end table
2216
2217All other characters in the format string must have a matching character
2218in the input string.  Exceptions are white spaces in the input string
2219which can match zero or more whitespace characters in the format string.
2220
2221@strong{Portability Note:} The XPG standard advises applications to use
2222at least one whitespace character (as specified by @code{isspace}) or
2223other non-alphanumeric characters between any two conversion
2224specifications.  @Theglibc{} does not have this limitation but
2225other libraries might have trouble parsing formats like
2226@code{"%d%m%Y%H%M%S"}.
2227
2228The @code{strptime} function processes the input string from right to
2229left.  Each of the three possible input elements (white space, literal,
2230or format) are handled one after the other.  If the input cannot be
2231matched to the format string the function stops.  The remainder of the
2232format and input strings are not processed.
2233
2234The function returns a pointer to the first character it was unable to
2235process.  If the input string contains more characters than required by
2236the format string the return value points right after the last consumed
2237input character.  If the whole input string is consumed the return value
2238points to the @code{NULL} byte at the end of the string.  If an error
2239occurs, i.e., @code{strptime} fails to match all of the format string,
2240the function returns @code{NULL}.
2241@end deftypefun
2242
2243The specification of the function in the XPG standard is rather vague,
2244leaving out a few important pieces of information.  Most importantly, it
2245does not specify what happens to those elements of @var{tm} which are
2246not directly initialized by the different formats.  The
2247implementations on different Unix systems vary here.
2248
2249The @glibcadj{} implementation does not touch those fields which are not
2250directly initialized.  Exceptions are the @code{tm_wday} and
2251@code{tm_yday} elements, which are recomputed if any of the year, month,
2252or date elements changed.  This has two implications:
2253
2254@itemize @bullet
2255@item
2256Before calling the @code{strptime} function for a new input string, you
2257should prepare the @var{tm} structure you pass.  Normally this will mean
2258initializing all values to zero.  Alternatively, you can set all
2259fields to values like @code{INT_MAX}, allowing you to determine which
2260elements were set by the function call.  Zero does not work here since
2261it is a valid value for many of the fields.
2262
2263Careful initialization is necessary if you want to find out whether a
2264certain field in @var{tm} was initialized by the function call.
2265
2266@item
2267You can construct a @code{struct tm} value with several consecutive
2268@code{strptime} calls.  A useful application of this is e.g. the parsing
2269of two separate strings, one containing date information and the other
2270time information.  By parsing one after the other without clearing the
2271structure in-between, you can construct a complete broken-down time.
2272@end itemize
2273
2274The following example shows a function which parses a string which
2275contains the date information in either US style or @w{ISO 8601} form:
2276
2277@smallexample
2278const char *
2279parse_date (const char *input, struct tm *tm)
2280@{
2281  const char *cp;
2282
2283  /* @r{First clear the result structure.}  */
2284  memset (tm, '\0', sizeof (*tm));
2285
2286  /* @r{Try the ISO format first.}  */
2287  cp = strptime (input, "%F", tm);
2288  if (cp == NULL)
2289    @{
2290      /* @r{Does not match.  Try the US form.}  */
2291      cp = strptime (input, "%D", tm);
2292    @}
2293
2294  return cp;
2295@}
2296@end smallexample
2297
2298@node General Time String Parsing
2299@subsubsection A More User-friendly Way to Parse Times and Dates
2300
2301The Unix standard defines another function for parsing date strings.
2302The interface is weird, but if the function happens to suit your
2303application it is just fine.  It is problematic to use this function
2304in multi-threaded programs or libraries, since it returns a pointer to
2305a static variable, and uses a global variable and global state (an
2306environment variable).
2307
2308@defvar getdate_err
2309@standards{Unix98, time.h}
2310This variable of type @code{int} contains the error code of the last
2311unsuccessful call to @code{getdate}.  Defined values are:
2312
2313@table @math
2314@item 1
2315The environment variable @code{DATEMSK} is not defined or null.
2316@item 2
2317The template file denoted by the @code{DATEMSK} environment variable
2318cannot be opened.
2319@item 3
2320Information about the template file cannot retrieved.
2321@item 4
2322The template file is not a regular file.
2323@item 5
2324An I/O error occurred while reading the template file.
2325@item 6
2326Not enough memory available to execute the function.
2327@item 7
2328The template file contains no matching template.
2329@item 8
2330The input date is invalid, but would match a template otherwise.  This
2331includes dates like February 31st, and dates which cannot be represented
2332in a @code{time_t} variable.
2333@end table
2334@end defvar
2335
2336@deftypefun {struct tm *} getdate (const char *@var{string})
2337@standards{Unix98, time.h}
2338@safety{@prelim{}@mtunsafe{@mtasurace{:getdate} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
2339@c getdate @mtasurace:getdate @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2340@c  getdate_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2341The interface to @code{getdate} is the simplest possible for a function
2342to parse a string and return the value.  @var{string} is the input
2343string and the result is returned in a statically-allocated variable.
2344
2345The details about how the string is processed are hidden from the user.
2346In fact, they can be outside the control of the program.  Which formats
2347are recognized is controlled by the file named by the environment
2348variable @code{DATEMSK}.  This file should contain
2349lines of valid format strings which could be passed to @code{strptime}.
2350
2351The @code{getdate} function reads these format strings one after the
2352other and tries to match the input string.  The first line which
2353completely matches the input string is used.
2354
2355Elements not initialized through the format string retain the values
2356present at the time of the @code{getdate} function call.
2357
2358The formats recognized by @code{getdate} are the same as for
2359@code{strptime}.  See above for an explanation.  There are only a few
2360extensions to the @code{strptime} behavior:
2361
2362@itemize @bullet
2363@item
2364If the @code{%Z} format is given the broken-down time is based on the
2365current time of the timezone matched, not of the current timezone of the
2366runtime environment.
2367
2368@emph{Note}: This is not implemented (currently).  The problem is that
2369timezone names are not unique.  If a fixed timezone is assumed for a
2370given string (say @code{EST} meaning US East Coast time), then uses for
2371countries other than the USA will fail.  So far we have found no good
2372solution to this.
2373
2374@item
2375If only the weekday is specified the selected day depends on the current
2376date.  If the current weekday is greater than or equal to the @code{tm_wday}
2377value the current week's day is chosen, otherwise the day next week is chosen.
2378
2379@item
2380A similar heuristic is used when only the month is given and not the
2381year.  If the month is greater than or equal to the current month, then
2382the current year is used.  Otherwise it wraps to next year.  The first
2383day of the month is assumed if one is not explicitly specified.
2384
2385@item
2386The current hour, minute, and second are used if the appropriate value is
2387not set through the format.
2388
2389@item
2390If no date is given tomorrow's date is used if the time is
2391smaller than the current time.  Otherwise today's date is taken.
2392@end itemize
2393
2394It should be noted that the format in the template file need not only
2395contain format elements.  The following is a list of possible format
2396strings (taken from the Unix standard):
2397
2398@smallexample
2399%m
2400%A %B %d, %Y %H:%M:%S
2401%A
2402%B
2403%m/%d/%y %I %p
2404%d,%m,%Y %H:%M
2405at %A the %dst of %B in %Y
2406run job at %I %p,%B %dnd
2407%A den %d. %B %Y %H.%M Uhr
2408@end smallexample
2409
2410As you can see, the template list can contain very specific strings like
2411@code{run job at %I %p,%B %dnd}.  Using the above list of templates and
2412assuming the current time is Mon Sep 22 12:19:47 EDT 1986, we can obtain the
2413following results for the given input.
2414
2415@multitable {xxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
2416@item        Input @tab     Match @tab Result
2417@item        Mon @tab       %a @tab    Mon Sep 22 12:19:47 EDT 1986
2418@item        Sun @tab       %a @tab    Sun Sep 28 12:19:47 EDT 1986
2419@item        Fri @tab       %a @tab    Fri Sep 26 12:19:47 EDT 1986
2420@item        September @tab %B @tab    Mon Sep 1 12:19:47 EDT 1986
2421@item        January @tab   %B @tab    Thu Jan 1 12:19:47 EST 1987
2422@item        December @tab  %B @tab    Mon Dec 1 12:19:47 EST 1986
2423@item        Sep Mon @tab   %b %a @tab Mon Sep 1 12:19:47 EDT 1986
2424@item        Jan Fri @tab   %b %a @tab Fri Jan 2 12:19:47 EST 1987
2425@item        Dec Mon @tab   %b %a @tab Mon Dec 1 12:19:47 EST 1986
2426@item        Jan Wed 1989 @tab  %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
2427@item        Fri 9 @tab     %a %H @tab Fri Sep 26 09:00:00 EDT 1986
2428@item        Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
2429@item        10:30 @tab     %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
2430@item        13:30 @tab     %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
2431@end multitable
2432
2433The return value of the function is a pointer to a static variable of
2434type @w{@code{struct tm}}, or a null pointer if an error occurred.  The
2435result is only valid until the next @code{getdate} call, making this
2436function unusable in multi-threaded applications.
2437
2438The @code{errno} variable is @emph{not} changed.  Error conditions are
2439stored in the global variable @code{getdate_err}.  See the
2440description above for a list of the possible error values.
2441
2442@emph{Warning:} The @code{getdate} function should @emph{never} be
2443used in SUID-programs.  The reason is obvious: using the
2444@code{DATEMSK} environment variable you can get the function to open
2445any arbitrary file and chances are high that with some bogus input
2446(such as a binary file) the program will crash.
2447@end deftypefun
2448
2449@deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
2450@standards{GNU, time.h}
2451@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
2452@c getdate_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2453@c  getenv dup @mtsenv
2454@c  stat64 dup ok
2455@c  access dup ok
2456@c  fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
2457@c  fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
2458@c  isspace dup @mtslocale
2459@c  strlen dup ok
2460@c  malloc dup @ascuheap @acsmem
2461@c  fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
2462@c  memcpy dup ok
2463@c  getline dup @ascuheap @acsmem [no @asucorrupt @aculock @acucorrupt, exclusive]
2464@c  strptime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2465@c  feof_unlocked dup ok
2466@c  free dup @ascuheap @acsmem
2467@c  ferror_unlocked dup dup ok
2468@c  time dup ok
2469@c  localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2470@c  first_wday @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2471@c   memset dup ok
2472@c   mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2473@c  check_mday ok
2474@c  mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2475The @code{getdate_r} function is the reentrant counterpart of
2476@code{getdate}.  It does not use the global variable @code{getdate_err}
2477to signal an error, but instead returns an error code.  The same error
2478codes as described in the @code{getdate_err} documentation above are
2479used, with 0 meaning success.
2480
2481Moreover, @code{getdate_r} stores the broken-down time in the variable
2482of type @code{struct tm} pointed to by the second argument, rather than
2483in a static variable.
2484
2485This function is not defined in the Unix standard.  Nevertheless it is
2486available on some other Unix systems as well.
2487
2488The warning against using @code{getdate} in SUID-programs applies to
2489@code{getdate_r} as well.
2490@end deftypefun
2491
2492@node TZ Variable
2493@subsection Specifying the Time Zone with @code{TZ}
2494
2495In POSIX systems, a user can specify the time zone by means of the
2496@code{TZ} environment variable.  For information about how to set
2497environment variables, see @ref{Environment Variables}.  The functions
2498for accessing the time zone are declared in @file{time.h}.
2499@pindex time.h
2500@cindex time zone
2501
2502You should not normally need to set @code{TZ}.  If the system is
2503configured properly, the default time zone will be correct.  You might
2504set @code{TZ} if you are using a computer over a network from a
2505different time zone, and would like times reported to you in the time
2506zone local to you, rather than what is local to the computer.
2507
2508In POSIX.1 systems the value of the @code{TZ} variable can be in one of
2509three formats.  With @theglibc{}, the most common format is the
2510last one, which can specify a selection from a large database of time
2511zone information for many regions of the world.  The first two formats
2512are used to describe the time zone information directly, which is both
2513more cumbersome and less precise.  But the POSIX.1 standard only
2514specifies the details of the first two formats, so it is good to be
2515familiar with them in case you come across a POSIX.1 system that doesn't
2516support a time zone information database.
2517
2518The first format is used when there is no Daylight Saving Time (or
2519summer time) in the local time zone:
2520
2521@smallexample
2522@r{@var{std} @var{offset}}
2523@end smallexample
2524
2525The @var{std} string specifies the name of the time zone.  It must be
2526three or more characters long and must not contain a leading colon,
2527embedded digits, commas, nor plus and minus signs.  There is no space
2528character separating the time zone name from the @var{offset}, so these
2529restrictions are necessary to parse the specification correctly.
2530
2531The @var{offset} specifies the time value you must add to the local time
2532to get a Coordinated Universal Time value.  It has syntax like
2533[@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]].  This
2534is positive if the local time zone is west of the Prime Meridian and
2535negative if it is east.  The hour must be between @code{0} and
2536@code{24}, and the minute and seconds between @code{0} and @code{59}.
2537
2538For example, here is how we would specify Eastern Standard Time, but
2539without any Daylight Saving Time alternative:
2540
2541@smallexample
2542EST+5
2543@end smallexample
2544
2545The second format is used when there is Daylight Saving Time:
2546
2547@smallexample
2548@r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
2549@end smallexample
2550
2551The initial @var{std} and @var{offset} specify the standard time zone, as
2552described above.  The @var{dst} string and @var{offset} specify the name
2553and offset for the corresponding Daylight Saving Time zone; if the
2554@var{offset} is omitted, it defaults to one hour ahead of standard time.
2555
2556The remainder of the specification describes when Daylight Saving Time is
2557in effect.  The @var{start} field is when Daylight Saving Time goes into
2558effect and the @var{end} field is when the change is made back to standard
2559time.  The following formats are recognized for these fields:
2560
2561@table @code
2562@item J@var{n}
2563This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
2564February 29 is never counted, even in leap years.
2565
2566@item @var{n}
2567This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
2568February 29 is counted in leap years.
2569
2570@item M@var{m}.@var{w}.@var{d}
2571This specifies day @var{d} of week @var{w} of month @var{m}.  The day
2572@var{d} must be between @code{0} (Sunday) and @code{6}.  The week
2573@var{w} must be between @code{1} and @code{5}; week @code{1} is the
2574first week in which day @var{d} occurs, and week @code{5} specifies the
2575@emph{last} @var{d} day in the month.  The month @var{m} should be
2576between @code{1} and @code{12}.
2577@end table
2578
2579The @var{time} fields specify when, in the local time currently in
2580effect, the change to the other time occurs.  If omitted, the default is
2581@code{02:00:00}.  The hours part of the time fields can range from
2582@minus{}167 through 167; this is an extension to POSIX.1, which allows
2583only the range 0 through 24.
2584
2585Here are some example @code{TZ} values, including the appropriate
2586Daylight Saving Time and its dates of applicability.  In North
2587American Eastern Standard Time (EST) and Eastern Daylight Time (EDT),
2588the normal offset from UTC is 5 hours; since this is
2589west of the prime meridian, the sign is positive.  Summer time begins on
2590March's second Sunday at 2:00am, and ends on November's first Sunday
2591at 2:00am.
2592
2593@smallexample
2594EST+5EDT,M3.2.0/2,M11.1.0/2
2595@end smallexample
2596
2597Israel Standard Time (IST) and Israel Daylight Time (IDT) are 2 hours
2598ahead of the prime meridian in winter, springing forward an hour on
2599March's fourth Thursday at 26:00 (i.e., 02:00 on the first Friday on or
2600after March 23), and falling back on October's last Sunday at 02:00.
2601
2602@smallexample
2603IST-2IDT,M3.4.4/26,M10.5.0
2604@end smallexample
2605
2606Western Argentina Summer Time (WARST) is 3 hours behind the prime
2607meridian all year.  There is a dummy fall-back transition on December
260831 at 25:00 daylight saving time (i.e., 24:00 standard time,
2609equivalent to January 1 at 00:00 standard time), and a simultaneous
2610spring-forward transition on January 1 at 00:00 standard time, so
2611daylight saving time is in effect all year and the initial @code{WART}
2612is a placeholder.
2613
2614@smallexample
2615WART4WARST,J1/0,J365/25
2616@end smallexample
2617
2618Western Greenland Time (WGT) and Western Greenland Summer Time (WGST)
2619are 3 hours behind UTC in the winter.  Its clocks follow the European
2620Union rules of springing forward by one hour on March's last Sunday at
262101:00 UTC (@minus{}02:00 local time) and falling back on October's
2622last Sunday at 01:00 UTC (@minus{}01:00 local time).
2623
2624@smallexample
2625WGT3WGST,M3.5.0/-2,M10.5.0/-1
2626@end smallexample
2627
2628The schedule of Daylight Saving Time in any particular jurisdiction has
2629changed over the years.  To be strictly correct, the conversion of dates
2630and times in the past should be based on the schedule that was in effect
2631then.  However, this format has no facilities to let you specify how the
2632schedule has changed from year to year.  The most you can do is specify
2633one particular schedule---usually the present day schedule---and this is
2634used to convert any date, no matter when.  For precise time zone
2635specifications, it is best to use the time zone information database
2636(see below).
2637
2638The third format looks like this:
2639
2640@smallexample
2641:@var{characters}
2642@end smallexample
2643
2644Each operating system interprets this format differently; in
2645@theglibc{}, @var{characters} is the name of a file which describes the time
2646zone.
2647
2648@pindex /etc/localtime
2649@pindex localtime
2650If the @code{TZ} environment variable does not have a value, the
2651operation chooses a time zone by default.  In @theglibc{}, the
2652default time zone is like the specification @samp{TZ=:/etc/localtime}
2653(or @samp{TZ=:/usr/local/etc/localtime}, depending on how @theglibc{}
2654was configured; @pxref{Installation}).  Other C libraries use their own
2655rule for choosing the default time zone, so there is little we can say
2656about them.
2657
2658@cindex time zone database
2659@pindex /usr/share/zoneinfo
2660@pindex zoneinfo
2661If @var{characters} begins with a slash, it is an absolute file name;
2662otherwise the library looks for the file
2663@w{@file{/usr/share/zoneinfo/@var{characters}}}.  The @file{zoneinfo}
2664directory contains data files describing local time zones in many
2665different parts of the world.  The names represent major cities, with
2666subdirectories for geographical areas; for example,
2667@file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
2668These data files are installed by the system administrator, who also
2669sets @file{/etc/localtime} to point to the data file for the local time
2670zone.  The files typically come from the @url{http://www.iana.org/time-zones,
2671Time Zone Database} of time zone and daylight saving time
2672information for most regions of the world, which is maintained by a
2673community of volunteers and put in the public domain.
2674
2675@node Time Zone Functions
2676@subsection Functions and Variables for Time Zones
2677
2678@deftypevar {char *} tzname [2]
2679@standards{POSIX.1, time.h}
2680The array @code{tzname} contains two strings, which are the standard
2681names of the pair of time zones (standard and Daylight
2682Saving) that the user has selected.  @code{tzname[0]} is the name of
2683the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
2684is the name for the time zone when Daylight Saving Time is in use (for
2685example, @code{"EDT"}).  These correspond to the @var{std} and @var{dst}
2686strings (respectively) from the @code{TZ} environment variable.  If
2687Daylight Saving Time is never used, @code{tzname[1]} is the empty string.
2688
2689The @code{tzname} array is initialized from the @code{TZ} environment
2690variable whenever @code{tzset}, @code{ctime}, @code{strftime},
2691@code{mktime}, or @code{localtime} is called.  If multiple abbreviations
2692have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
2693Time and Eastern Daylight Time), the array contains the most recent
2694abbreviation.
2695
2696The @code{tzname} array is required for POSIX.1 compatibility, but in
2697GNU programs it is better to use the @code{tm_zone} member of the
2698broken-down time structure, since @code{tm_zone} reports the correct
2699abbreviation even when it is not the latest one.
2700
2701Though the strings are declared as @code{char *} the user must refrain
2702from modifying these strings.  Modifying the strings will almost certainly
2703lead to trouble.
2704
2705@end deftypevar
2706
2707@deftypefun void tzset (void)
2708@standards{POSIX.1, time.h}
2709@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
2710@c tzset @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2711@c  libc_lock_lock dup @asulock @aculock
2712@c  tzset_internal dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2713@c  libc_lock_unlock dup @aculock
2714The @code{tzset} function initializes the @code{tzname} variable from
2715the value of the @code{TZ} environment variable.  It is not usually
2716necessary for your program to call this function, because it is called
2717automatically when you use the other time conversion functions that
2718depend on the time zone.
2719@end deftypefun
2720
2721The following variables are defined for compatibility with System V
2722Unix.  Like @code{tzname}, these variables are set by calling
2723@code{tzset} or the other time conversion functions.
2724
2725@deftypevar {long int} timezone
2726@standards{SVID, time.h}
2727This contains the difference between UTC and the latest local standard
2728time, in seconds west of UTC.  For example, in the U.S. Eastern time
2729zone, the value is @code{5*60*60}.  Unlike the @code{tm_gmtoff} member
2730of the broken-down time structure, this value is not adjusted for
2731daylight saving, and its sign is reversed.  In GNU programs it is better
2732to use @code{tm_gmtoff}, since it contains the correct offset even when
2733it is not the latest one.
2734@end deftypevar
2735
2736@deftypevar int daylight
2737@standards{SVID, time.h}
2738This variable has a nonzero value if Daylight Saving Time rules apply.
2739A nonzero value does not necessarily mean that Daylight Saving Time is
2740now in effect; it means only that Daylight Saving Time is sometimes in
2741effect.
2742@end deftypevar
2743
2744@node Time Functions Example
2745@subsection Time Functions Example
2746
2747Here is an example program showing the use of some of the calendar time
2748functions.
2749
2750@smallexample
2751@include strftim.c.texi
2752@end smallexample
2753
2754It produces output like this:
2755
2756@smallexample
2757Wed Jul 31 13:02:36 1991
2758Today is Wednesday, July 31.
2759The time is 01:02 PM.
2760@end smallexample
2761
2762
2763@node Setting an Alarm
2764@section Setting an Alarm
2765
2766The @code{alarm} and @code{setitimer} functions provide a mechanism for a
2767process to interrupt itself in the future.  They do this by setting a
2768timer; when the timer expires, the process receives a signal.
2769
2770@cindex setting an alarm
2771@cindex interval timer, setting
2772@cindex alarms, setting
2773@cindex timers, setting
2774Each process has three independent interval timers available:
2775
2776@itemize @bullet
2777@item
2778A real-time timer that counts elapsed time.  This timer sends a
2779@code{SIGALRM} signal to the process when it expires.
2780@cindex real-time timer
2781@cindex timer, real-time
2782
2783@item
2784A virtual timer that counts processor time used by the process.  This timer
2785sends a @code{SIGVTALRM} signal to the process when it expires.
2786@cindex virtual timer
2787@cindex timer, virtual
2788
2789@item
2790A profiling timer that counts both processor time used by the process,
2791and processor time spent in system calls on behalf of the process.  This
2792timer sends a @code{SIGPROF} signal to the process when it expires.
2793@cindex profiling timer
2794@cindex timer, profiling
2795
2796This timer is useful for profiling in interpreters.  The interval timer
2797mechanism does not have the fine granularity necessary for profiling
2798native code.
2799@c @xref{profil} !!!
2800@end itemize
2801
2802You can only have one timer of each kind set at any given time.  If you
2803set a timer that has not yet expired, that timer is simply reset to the
2804new value.
2805
2806You should establish a handler for the appropriate alarm signal using
2807@code{signal} or @code{sigaction} before issuing a call to
2808@code{setitimer} or @code{alarm}.  Otherwise, an unusual chain of events
2809could cause the timer to expire before your program establishes the
2810handler.  In this case it would be terminated, since termination is the
2811default action for the alarm signals.  @xref{Signal Handling}.
2812
2813To be able to use the alarm function to interrupt a system call which
2814might block otherwise indefinitely it is important to @emph{not} set the
2815@code{SA_RESTART} flag when registering the signal handler using
2816@code{sigaction}.  When not using @code{sigaction} things get even
2817uglier: the @code{signal} function has fixed semantics with respect
2818to restarts.  The BSD semantics for this function is to set the flag.
2819Therefore, if @code{sigaction} for whatever reason cannot be used, it is
2820necessary to use @code{sysv_signal} and not @code{signal}.
2821
2822The @code{setitimer} function is the primary means for setting an alarm.
2823This facility is declared in the header file @file{sys/time.h}.  The
2824@code{alarm} function, declared in @file{unistd.h}, provides a somewhat
2825simpler interface for setting the real-time timer.
2826@pindex unistd.h
2827@pindex sys/time.h
2828
2829@deftp {Data Type} {struct itimerval}
2830@standards{BSD, sys/time.h}
2831This structure is used to specify when a timer should expire.  It contains
2832the following members:
2833@table @code
2834@item struct timeval it_interval
2835This is the period between successive timer interrupts.  If zero, the
2836alarm will only be sent once.
2837
2838@item struct timeval it_value
2839This is the period between now and the first timer interrupt.  If zero,
2840the alarm is disabled.
2841@end table
2842
2843The @code{struct timeval} data type is described in @ref{Time Types}.
2844@end deftp
2845
2846@deftypefun int setitimer (int @var{which}, const struct itimerval *@var{new}, struct itimerval *@var{old})
2847@standards{BSD, sys/time.h}
2848@safety{@prelim{}@mtsafe{@mtstimer{}}@assafe{}@acsafe{}}
2849@c This function is marked with @mtstimer because the same set of timers
2850@c is shared by all threads of a process, so calling it in one thread
2851@c may interfere with timers set by another thread.  This interference
2852@c is not regarded as destructive, because the interface specification
2853@c makes this overriding while returning the previous value the expected
2854@c behavior, and the kernel will serialize concurrent calls so that the
2855@c last one prevails, with each call getting the timer information from
2856@c the timer installed by the previous call in that serialization.
2857The @code{setitimer} function sets the timer specified by @var{which}
2858according to @var{new}.  The @var{which} argument can have a value of
2859@code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
2860
2861If @var{old} is not a null pointer, @code{setitimer} returns information
2862about any previous unexpired timer of the same kind in the structure it
2863points to.
2864
2865The return value is @code{0} on success and @code{-1} on failure.  The
2866following @code{errno} error conditions are defined for this function:
2867
2868@table @code
2869@item EINVAL
2870The timer period is too large.
2871@end table
2872@end deftypefun
2873
2874@deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
2875@standards{BSD, sys/time.h}
2876@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2877The @code{getitimer} function stores information about the timer specified
2878by @var{which} in the structure pointed at by @var{old}.
2879
2880The return value and error conditions are the same as for @code{setitimer}.
2881@end deftypefun
2882
2883@vtable @code
2884@item ITIMER_REAL
2885@standards{BSD, sys/time.h}
2886This constant can be used as the @var{which} argument to the
2887@code{setitimer} and @code{getitimer} functions to specify the real-time
2888timer.
2889
2890@item ITIMER_VIRTUAL
2891@standards{BSD, sys/time.h}
2892This constant can be used as the @var{which} argument to the
2893@code{setitimer} and @code{getitimer} functions to specify the virtual
2894timer.
2895
2896@item ITIMER_PROF
2897@standards{BSD, sys/time.h}
2898This constant can be used as the @var{which} argument to the
2899@code{setitimer} and @code{getitimer} functions to specify the profiling
2900timer.
2901@end vtable
2902
2903@deftypefun {unsigned int} alarm (unsigned int @var{seconds})
2904@standards{POSIX.1, unistd.h}
2905@safety{@prelim{}@mtsafe{@mtstimer{}}@assafe{}@acsafe{}}
2906@c Wrapper for setitimer.
2907The @code{alarm} function sets the real-time timer to expire in
2908@var{seconds} seconds.  If you want to cancel any existing alarm, you
2909can do this by calling @code{alarm} with a @var{seconds} argument of
2910zero.
2911
2912The return value indicates how many seconds remain before the previous
2913alarm would have been sent.  If there was no previous alarm, @code{alarm}
2914returns zero.
2915@end deftypefun
2916
2917The @code{alarm} function could be defined in terms of @code{setitimer}
2918like this:
2919
2920@smallexample
2921unsigned int
2922alarm (unsigned int seconds)
2923@{
2924  struct itimerval old, new;
2925  new.it_interval.tv_usec = 0;
2926  new.it_interval.tv_sec = 0;
2927  new.it_value.tv_usec = 0;
2928  new.it_value.tv_sec = (long int) seconds;
2929  if (setitimer (ITIMER_REAL, &new, &old) < 0)
2930    return 0;
2931  else
2932    return old.it_value.tv_sec;
2933@}
2934@end smallexample
2935
2936There is an example showing the use of the @code{alarm} function in
2937@ref{Handler Returns}.
2938
2939If you simply want your process to wait for a given number of seconds,
2940you should use the @code{sleep} function.  @xref{Sleeping}.
2941
2942You shouldn't count on the signal arriving precisely when the timer
2943expires.  In a multiprocessing environment there is typically some
2944amount of delay involved.
2945
2946@strong{Portability Note:} The @code{setitimer} and @code{getitimer}
2947functions are derived from BSD Unix, while the @code{alarm} function is
2948specified by the POSIX.1 standard.  @code{setitimer} is more powerful than
2949@code{alarm}, but @code{alarm} is more widely used.
2950
2951@node Sleeping
2952@section Sleeping
2953
2954The function @code{sleep} gives a simple way to make the program wait
2955for a short interval.  If your program doesn't use signals (except to
2956terminate), then you can expect @code{sleep} to wait reliably throughout
2957the specified interval.  Otherwise, @code{sleep} can return sooner if a
2958signal arrives; if you want to wait for a given interval regardless of
2959signals, use @code{select} (@pxref{Waiting for I/O}) and don't specify
2960any descriptors to wait for.
2961@c !!! select can get EINTR; using SA_RESTART makes sleep win too.
2962
2963@deftypefun {unsigned int} sleep (unsigned int @var{seconds})
2964@standards{POSIX.1, unistd.h}
2965@safety{@prelim{}@mtunsafe{@mtascusig{:SIGCHLD/linux}}@asunsafe{}@acunsafe{}}
2966@c On Mach, it uses ports and calls time.  On generic posix, it calls
2967@c nanosleep.  On Linux, it temporarily blocks SIGCHLD, which is MT- and
2968@c AS-Unsafe, and in a way that makes it AC-Unsafe (C-unsafe, even!).
2969The @code{sleep} function waits for @var{seconds} seconds or until a signal
2970is delivered, whichever happens first.
2971
2972If @code{sleep} returns because the requested interval is over,
2973it returns a value of zero.  If it returns because of delivery of a
2974signal, its return value is the remaining time in the sleep interval.
2975
2976The @code{sleep} function is declared in @file{unistd.h}.
2977@end deftypefun
2978
2979Resist the temptation to implement a sleep for a fixed amount of time by
2980using the return value of @code{sleep}, when nonzero, to call
2981@code{sleep} again.  This will work with a certain amount of accuracy as
2982long as signals arrive infrequently.  But each signal can cause the
2983eventual wakeup time to be off by an additional second or so.  Suppose a
2984few signals happen to arrive in rapid succession by bad luck---there is
2985no limit on how much this could shorten or lengthen the wait.
2986
2987Instead, compute the calendar time at which the program should stop
2988waiting, and keep trying to wait until that calendar time.  This won't
2989be off by more than a second.  With just a little more work, you can use
2990@code{select} and make the waiting period quite accurate.  (Of course,
2991heavy system load can cause additional unavoidable delays---unless the
2992machine is dedicated to one application, there is no way you can avoid
2993this.)
2994
2995On some systems, @code{sleep} can do strange things if your program uses
2996@code{SIGALRM} explicitly.  Even if @code{SIGALRM} signals are being
2997ignored or blocked when @code{sleep} is called, @code{sleep} might
2998return prematurely on delivery of a @code{SIGALRM} signal.  If you have
2999established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
3000signal is delivered while the process is sleeping, the action taken
3001might be just to cause @code{sleep} to return instead of invoking your
3002handler.  And, if @code{sleep} is interrupted by delivery of a signal
3003whose handler requests an alarm or alters the handling of @code{SIGALRM},
3004this handler and @code{sleep} will interfere.
3005
3006On @gnusystems{}, it is safe to use @code{sleep} and @code{SIGALRM} in
3007the same program, because @code{sleep} does not work by means of
3008@code{SIGALRM}.
3009
3010@deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
3011@standards{POSIX.1, time.h}
3012@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3013@c On Linux, it's a syscall.  On Mach, it calls gettimeofday and uses
3014@c ports.
3015If resolution to seconds is not enough the @code{nanosleep} function can
3016be used.  As the name suggests the sleep interval can be specified in
3017nanoseconds.  The actual elapsed time of the sleep interval might be
3018longer since the system rounds the elapsed time you request up to the
3019next integer multiple of the actual resolution the system can deliver.
3020
3021@code{*@var{requested_time}} is the elapsed time of the interval you
3022want to sleep.
3023
3024The function returns as @code{*@var{remaining}} the elapsed time left
3025in the interval for which you requested to sleep.  If the interval
3026completed without getting interrupted by a signal, this is zero.
3027
3028@code{struct timespec} is described in @ref{Time Types}.
3029
3030If the function returns because the interval is over the return value is
3031zero.  If the function returns @math{-1} the global variable @code{errno}
3032is set to the following values:
3033
3034@table @code
3035@item EINTR
3036The call was interrupted because a signal was delivered to the thread.
3037If the @var{remaining} parameter is not the null pointer the structure
3038pointed to by @var{remaining} is updated to contain the remaining
3039elapsed time.
3040
3041@item EINVAL
3042The nanosecond value in the @var{requested_time} parameter contains an
3043illegal value.  Either the value is negative or greater than or equal to
30441000 million.
3045@end table
3046
3047This function is a cancellation point in multi-threaded programs.  This
3048is a problem if the thread allocates some resources (like memory, file
3049descriptors, semaphores or whatever) at the time @code{nanosleep} is
3050called.  If the thread gets canceled these resources stay allocated
3051until the program ends.  To avoid this calls to @code{nanosleep} should
3052be protected using cancellation handlers.
3053@c ref pthread_cleanup_push / pthread_cleanup_pop
3054
3055The @code{nanosleep} function is declared in @file{time.h}.
3056@end deftypefun
3057