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