]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/time.texi
.
[thirdparty/glibc.git] / manual / time.texi
CommitLineData
5ce8f203 1@node Date and Time, Resource Usage And Limitation, Arithmetic, Top
7a68c94a 2@c %MENU% Functions for getting the date and time and formatting them nicely
28f540f4
RM
3@chapter Date and Time
4
5This chapter describes functions for manipulating dates and times,
99a20616
UD
6including functions for determining what time it is and conversion
7between different time representations.
28f540f4
RM
8
9@menu
99a20616
UD
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.
28f540f4
RM
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.
28f540f4
RM
16@end menu
17
5ce8f203 18
99a20616
UD
19@node Time Basics
20@section Time Basics
21@cindex time
5ce8f203 22
99a20616
UD
23Discussing time in a technical manual can be difficult because the word
24``time'' in English refers to lots of different things. In this manual,
25we use a rigorous terminology to avoid confusion, and the only thing we
26use the simple word ``time'' for is to talk about the abstract concept.
27
28A @dfn{calendar time} is a point in the time continuum, for example
29November 4, 1990 at 18:02.5 UTC. Sometimes this is called ``absolute
30time''.
31@cindex calendar time
32
33We don't speak of a ``date'', because that is inherent in a calendar
34time.
35@cindex date
36
37An @dfn{interval} is a contiguous part of the time continuum between two
38calendar times, for example the hour between 9:00 and 10:00 on July 4,
391980.
40@cindex interval
41
42An @dfn{elapsed time} is the length of an interval, for example, 35
43minutes. People sometimes sloppily use the word ``interval'' to refer
44to the elapsed time of some interval.
45@cindex elapsed time
46@cindex time, elapsed
47
48An @dfn{amount of time} is a sum of elapsed times, which need not be of
49any specific intervals. For example, the amount of time it takes to
50read a book might be 9 hours, independently of when and in how many
51sittings it is read.
52
53A @dfn{period} is the elapsed time of an interval between two events,
54especially when they are part of a sequence of regularly repeating
55events.
56@cindex period of time
57
58@dfn{CPU time} is like calendar time, except that it is based on the
59subset of the time continuum when a particular process is actively
60using a CPU. CPU time is, therefore, relative to a process.
28f540f4 61@cindex CPU time
99a20616
UD
62
63@dfn{Processor time} is an amount of time that a CPU is in use. In
64fact, it's a basic system resource, since there's a limit to how much
65can exist in any given interval (that limit is the elapsed time of the
66interval times the number of CPUs in the processor). People often call
67this CPU time, but we reserve the latter term in this manual for the
68definition above.
28f540f4 69@cindex processor time
99a20616
UD
70
71@node Elapsed Time
72@section Elapsed Time
73@cindex elapsed time
74
75One way to represent an elapsed time is with a simple arithmetic data
76type, as with the following function to compute the elapsed time between
77two calendar times. This function is declared in @file{time.h}.
78
79@comment time.h
80@comment ISO
81@deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
82The @code{difftime} function returns the number of seconds of elapsed
83time between calendar time @var{time1} and calendar time @var{time0}, as
84a value of type @code{double}. The difference ignores leap seconds
85unless leap second support is enabled.
86
87In the GNU system, you can simply subtract @code{time_t} values. But on
88other systems, the @code{time_t} data type might use some other encoding
89where subtraction doesn't work directly.
90@end deftypefun
91
92The GNU C library provides two data types specifically for representing
93an elapsed time. They are used by various GNU C library functions, and
94you can use them for your own purposes too. They're exactly the same
95except that one has a resolution in microseconds, and the other, newer
96one, is in nanoseconds.
97
98@comment sys/time.h
99@comment BSD
100@deftp {Data Type} {struct timeval}
101@cindex timeval
102The @code{struct timeval} structure represents an elapsed time. It is
103declared in @file{sys/time.h} and has the following members:
104
105@table @code
106@item long int tv_sec
107This represents the number of whole seconds of elapsed time.
108
109@item long int tv_usec
110This is the rest of the elapsed time (a fraction of a second),
111represented as the number of microseconds. It is always less than one
112million.
113
114@end table
115@end deftp
116
117@comment sys/time.h
118@comment POSIX.1
119@deftp {Data Type} {struct timespec}
120@cindex timespec
121The @code{struct timespec} structure represents an elapsed time. It is
122declared in @file{time.h} and has the following members:
123
124@table @code
125@item long int tv_sec
126This represents the number of whole seconds of elapsed time.
127
128@item long int tv_nsec
129This is the rest of the elapsed time (a fraction of a second),
130represented as the number of nanoseconds. It is always less than one
131billion.
132
133@end table
134@end deftp
135
136It is often necessary to subtract two values of type @w{@code{struct
137timeval}} or @w{@code{struct timespec}}. Here is the best way to do
138this. It works even on some peculiar operating systems where the
139@code{tv_sec} member has an unsigned type.
140
141@smallexample
142/* @r{Subtract the `struct timeval' values X and Y,}
143 @r{storing the result in RESULT.}
144 @r{Return 1 if the difference is negative, otherwise 0.} */
145
146int
147timeval_subtract (result, x, y)
148 struct timeval *result, *x, *y;
149@{
150 /* @r{Perform the carry for the later subtraction by updating @var{y}.} */
151 if (x->tv_usec < y->tv_usec) @{
152 int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
153 y->tv_usec -= 1000000 * nsec;
154 y->tv_sec += nsec;
155 @}
156 if (x->tv_usec - y->tv_usec > 1000000) @{
157 int nsec = (x->tv_usec - y->tv_usec) / 1000000;
158 y->tv_usec += 1000000 * nsec;
159 y->tv_sec -= nsec;
160 @}
161
162 /* @r{Compute the time remaining to wait.}
163 @r{@code{tv_usec} is certainly positive.} */
164 result->tv_sec = x->tv_sec - y->tv_sec;
165 result->tv_usec = x->tv_usec - y->tv_usec;
166
167 /* @r{Return 1 if result is negative.} */
168 return x->tv_sec < y->tv_sec;
169@}
170@end smallexample
171
b642f101 172Common functions that use @code{struct timeval} are @code{gettimeofday}
99a20616
UD
173and @code{settimeofday}.
174
175
176There are no GNU C library functions specifically oriented toward
177dealing with elapsed times, but the calendar time, processor time, and
178alarm and sleeping functions have a lot to do with them.
179
180
181@node Processor And CPU Time
182@section Processor And CPU Time
183
184If you're trying to optimize your program or measure its efficiency,
185it's very useful to know how much processor time it uses. For that,
186calendar time and elapsed times are useless because a process may spend
187time waiting for I/O or for other processes to use the CPU. However,
188you can get the information with the functions in this section.
189
190CPU time (@pxref{Time Basics}) is represented by the data type
191@code{clock_t}, which is a number of @dfn{clock ticks}. It gives the
192total amount of time a process has actively used a CPU since some
193arbitrary event. On the GNU system, that event is the creation of the
194process. While arbitrary in general, the event is always the same event
195for any particular process, so you can always measure how much time on
32c075e1 196the CPU a particular computation takes by examinining the process' CPU
99a20616
UD
197time before and after the computation.
198@cindex CPU time
28f540f4
RM
199@cindex clock ticks
200@cindex ticks, clock
99a20616
UD
201
202In the GNU system, @code{clock_t} is equivalent to @code{long int} and
203@code{CLOCKS_PER_SEC} is an integer value. But in other systems, both
204@code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer
205or floating-point types. Casting CPU time values to @code{double}, as
206in the example above, makes sure that operations such as arithmetic and
207printing work properly and consistently no matter what the underlying
208representation is.
209
210Note that the clock can wrap around. On a 32bit system with
211@code{CLOCKS_PER_SEC} set to one million this function will return the
212same value approximately every 72 minutes.
213
214For additional functions to examine a process' use of processor time,
215and to control it, @xref{Resource Usage And Limitation}.
216
28f540f4
RM
217
218@menu
99a20616
UD
219* CPU Time:: The @code{clock} function.
220* Processor Time:: The @code{times} function.
28f540f4
RM
221@end menu
222
99a20616
UD
223@node CPU Time
224@subsection CPU Time Inquiry
28f540f4 225
99a20616
UD
226To get a process' CPU time, you can use the @code{clock} function. This
227facility is declared in the header file @file{time.h}.
28f540f4
RM
228@pindex time.h
229
99a20616
UD
230In typical usage, you call the @code{clock} function at the beginning
231and end of the interval you want to time, subtract the values, and then
232divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second)
233to get processor time, like this:
28f540f4
RM
234
235@smallexample
236@group
237#include <time.h>
238
239clock_t start, end;
99a20616 240double cpu_time_used;
28f540f4
RM
241
242start = clock();
243@dots{} /* @r{Do the work.} */
244end = clock();
99a20616 245cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
28f540f4
RM
246@end group
247@end smallexample
248
99a20616
UD
249Do not use a single CPU time as an amount of time; it doesn't work that
250way. Either do a subtraction as shown above or query processor time
251directly. @xref{Processor Time}.
252
28f540f4 253Different computers and operating systems vary wildly in how they keep
99a20616
UD
254track of CPU time. It's common for the internal processor clock
255to have a resolution somewhere between a hundredth and millionth of a
28f540f4
RM
256second.
257
28f540f4 258@comment time.h
f65fd747 259@comment ISO
28f540f4
RM
260@deftypevr Macro int CLOCKS_PER_SEC
261The value of this macro is the number of clock ticks per second measured
99a20616 262by the @code{clock} function. POSIX requires that this value be one
ce33f7be 263million independent of the actual resolution.
28f540f4
RM
264@end deftypevr
265
266@comment time.h
267@comment POSIX.1
268@deftypevr Macro int CLK_TCK
01cdeca0 269This is an obsolete name for @code{CLOCKS_PER_SEC}.
28f540f4
RM
270@end deftypevr
271
272@comment time.h
f65fd747 273@comment ISO
28f540f4
RM
274@deftp {Data Type} clock_t
275This is the type of the value returned by the @code{clock} function.
99a20616 276Values of type @code{clock_t} are numbers of clock ticks.
28f540f4
RM
277@end deftp
278
279@comment time.h
f65fd747 280@comment ISO
28f540f4 281@deftypefun clock_t clock (void)
99a20616 282This function returns the calling process' current CPU time. If the CPU
28f540f4
RM
283time is not available or cannot be represented, @code{clock} returns the
284value @code{(clock_t)(-1)}.
285@end deftypefun
286
287
99a20616
UD
288@node Processor Time
289@subsection Processor Time Inquiry
28f540f4 290
99a20616
UD
291The @code{times} function returns information about a process'
292consumption of processor time in a @w{@code{struct tms}} object, in
293addition to the process' CPU time. @xref{Time Basics}. You should
28f540f4 294include the header file @file{sys/times.h} to use this facility.
99a20616
UD
295@cindex processor time
296@cindex CPU time
28f540f4
RM
297@pindex sys/times.h
298
299@comment sys/times.h
300@comment POSIX.1
301@deftp {Data Type} {struct tms}
302The @code{tms} structure is used to return information about process
303times. It contains at least the following members:
304
305@table @code
306@item clock_t tms_utime
99a20616
UD
307This is the total processor time the calling process has used in
308executing the instructions of its program.
28f540f4
RM
309
310@item clock_t tms_stime
99a20616
UD
311This is the processor time the system has used on behalf of the calling
312process.
28f540f4
RM
313
314@item clock_t tms_cutime
315This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
316values of all terminated child processes of the calling process, whose
317status has been reported to the parent process by @code{wait} or
318@code{waitpid}; see @ref{Process Completion}. In other words, it
99a20616
UD
319represents the total processor time used in executing the instructions
320of all the terminated child processes of the calling process, excluding
321child processes which have not yet been reported by @code{wait} or
28f540f4 322@code{waitpid}.
99a20616 323@cindex child process
28f540f4
RM
324
325@item clock_t tms_cstime
99a20616
UD
326This is similar to @code{tms_cutime}, but represents the total processor
327time system has used on behalf of all the terminated child processes
328of the calling process.
28f540f4
RM
329@end table
330
99a20616
UD
331All of the times are given in numbers of clock ticks. Unlike CPU time,
332these are the actual amounts of time; not relative to any event.
333@xref{Creating a Process}.
28f540f4
RM
334@end deftp
335
336@comment sys/times.h
337@comment POSIX.1
338@deftypefun clock_t times (struct tms *@var{buffer})
339The @code{times} function stores the processor time information for
340the calling process in @var{buffer}.
341
99a20616
UD
342The return value is the calling process' CPU time (the same value you
343get from @code{clock()}. @code{times} returns @code{(clock_t)(-1)} to
344indicate failure.
28f540f4
RM
345@end deftypefun
346
347@strong{Portability Note:} The @code{clock} function described in
99a20616 348@ref{CPU Time} is specified by the @w{ISO C} standard. The
28f540f4 349@code{times} function is a feature of POSIX.1. In the GNU system, the
99a20616
UD
350CPU time is defined to be equivalent to the sum of the @code{tms_utime}
351and @code{tms_stime} fields returned by @code{times}.
28f540f4
RM
352
353@node Calendar Time
354@section Calendar Time
355
99a20616
UD
356This section describes facilities for keeping track of calendar time.
357@xref{Time Basics}.
28f540f4 358
3566d33c 359The GNU C library represents calendar time three ways:
28f540f4
RM
360
361@itemize @bullet
01cdeca0 362@item
3566d33c 363@dfn{Simple time} (the @code{time_t} data type) is a compact
99a20616
UD
364representation, typically giving the number of seconds of elapsed time
365since some implementation-specific base time.
3566d33c 366@cindex simple time
28f540f4
RM
367
368@item
99a20616
UD
369There is also a "high-resolution time" representation. Like simple
370time, this represents a calendar time as an elapsed time since a base
371time, but instead of measuring in whole seconds, it uses a @code{struct
372timeval} data type, which includes fractions of a second. Use this time
373representation instead of simple time when you need greater precision.
28f540f4
RM
374@cindex high-resolution time
375
376@item
3566d33c 377@dfn{Local time} or @dfn{broken-down time} (the @code{struct tm} data
99a20616 378type) represents a calendar time as a set of components specifying the
3566d33c 379year, month, and so on in the Gregorian calendar, for a specific time
99a20616
UD
380zone. This calendar time representation is usually used only to
381communicate with people.
28f540f4
RM
382@cindex local time
383@cindex broken-down time
3566d33c
UD
384@cindex Gregorian calendar
385@cindex calendar, Gregorian
28f540f4
RM
386@end itemize
387
388@menu
389* Simple Calendar Time:: Facilities for manipulating calendar time.
390* High-Resolution Calendar:: A time representation with greater precision.
391* Broken-down Time:: Facilities for manipulating local time.
3566d33c 392* High Accuracy Clock:: Maintaining a high accuracy system clock.
99a20616 393* Formatting Calendar Time:: Converting times to strings.
e9dcb080
UD
394* Parsing Date and Time:: Convert textual time and date information back
395 into broken-down time values.
28f540f4 396* TZ Variable:: How users specify the time zone.
01cdeca0 397* Time Zone Functions:: Functions to examine or specify the time zone.
28f540f4
RM
398* Time Functions Example:: An example program showing use of some of
399 the time functions.
400@end menu
401
402@node Simple Calendar Time
403@subsection Simple Calendar Time
404
3566d33c
UD
405This section describes the @code{time_t} data type for representing calendar
406time as simple time, and the functions which operate on simple time objects.
28f540f4
RM
407These facilities are declared in the header file @file{time.h}.
408@pindex time.h
409
410@cindex epoch
411@comment time.h
f65fd747 412@comment ISO
28f540f4 413@deftp {Data Type} time_t
3566d33c 414This is the data type used to represent simple time. Sometimes, it also
99a20616
UD
415represents an elapsed time. When interpreted as a calendar time value,
416it represents the number of seconds elapsed since 00:00:00 on January 1,
4171970, Coordinated Universal Time. (This calendar time is sometimes
418referred to as the @dfn{epoch}.) POSIX requires that this count not
419include leap seconds, but on some systems this count includes leap seconds
60092701 420if you set @code{TZ} to certain values (@pxref{TZ Variable}).
28f540f4 421
99a20616
UD
422Note that a simple time has no concept of local time zone. Calendar
423Time @var{T} is the same instant in time regardless of where on the
424globe the computer is.
3566d33c 425
60092701 426In the GNU C library, @code{time_t} is equivalent to @code{long int}.
28f540f4
RM
427In other systems, @code{time_t} might be either an integer or
428floating-point type.
429@end deftp
430
99a20616
UD
431The function @code{difftime} tells you the elapsed time between two
432simple calendar times, which is not always as easy to compute as just
433subtracting. @xref{Elapsed Time}.
28f540f4
RM
434
435@comment time.h
f65fd747 436@comment ISO
28f540f4 437@deftypefun time_t time (time_t *@var{result})
99a20616
UD
438The @code{time} function returns the current calendar time as a value of
439type @code{time_t}. If the argument @var{result} is not a null pointer,
440the calendar time value is also stored in @code{*@var{result}}. If the
441current calendar time is not available, the value
442@w{@code{(time_t)(-1)}} is returned.
28f540f4
RM
443@end deftypefun
444
3566d33c
UD
445@c The GNU C library implements stime() with a call to settimeofday() on
446@c Linux.
447@comment time.h
448@comment SVID, XPG
449@deftypefun int stime (time_t *@var{newtime})
32c075e1 450@code{stime} sets the system clock, i.e. it tells the system that the
99a20616 451current calendar time is @var{newtime}, where @code{newtime} is
3566d33c
UD
452interpreted as described in the above definition of @code{time_t}.
453
454@code{settimeofday} is a newer function which sets the system clock to
455better than one second precision. @code{settimeofday} is generally a
456better choice than @code{stime}. @xref{High-Resolution Calendar}.
457
458Only the superuser can set the system clock.
459
460If the function succeeds, the return value is zero. Otherwise, it is
461@code{-1} and @code{errno} is set accordingly:
462
463@table @code
464@item EPERM
465The process is not superuser.
466@end table
467@end deftypefun
468
469
28f540f4
RM
470
471@node High-Resolution Calendar
472@subsection High-Resolution Calendar
473
3566d33c 474The @code{time_t} data type used to represent simple times has a
28f540f4
RM
475resolution of only one second. Some applications need more precision.
476
477So, the GNU C library also contains functions which are capable of
478representing calendar times to a higher resolution than one second. The
479functions and the associated data types described in this section are
480declared in @file{sys/time.h}.
481@pindex sys/time.h
482
28f540f4
RM
483@comment sys/time.h
484@comment BSD
485@deftp {Data Type} {struct timezone}
486The @code{struct timezone} structure is used to hold minimal information
487about the local time zone. It has the following members:
488
489@table @code
490@item int tz_minuteswest
f0f1bf85 491This is the number of minutes west of UTC.
28f540f4
RM
492
493@item int tz_dsttime
76c23bac 494If nonzero, Daylight Saving Time applies during some part of the year.
28f540f4
RM
495@end table
496
497The @code{struct timezone} type is obsolete and should never be used.
498Instead, use the facilities described in @ref{Time Zone Functions}.
499@end deftp
500
28f540f4
RM
501@comment sys/time.h
502@comment BSD
503@deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
99a20616
UD
504The @code{gettimeofday} function returns the current calendar time as
505the elapsed time since the epoch in the @code{struct timeval} structure
506indicated by @var{tp}. (@pxref{Elapsed Time} for a description of
0cb71e02 507@code{struct timeval}). Information about the time zone is returned in
99a20616
UD
508the structure pointed at @var{tzp}. If the @var{tzp} argument is a null
509pointer, time zone information is ignored.
28f540f4
RM
510
511The return value is @code{0} on success and @code{-1} on failure. The
512following @code{errno} error condition is defined for this function:
513
514@table @code
515@item ENOSYS
516The operating system does not support getting time zone information, and
517@var{tzp} is not a null pointer. The GNU operating system does not
518support using @w{@code{struct timezone}} to represent time zone
519information; that is an obsolete feature of 4.3 BSD.
520Instead, use the facilities described in @ref{Time Zone Functions}.
521@end table
522@end deftypefun
523
524@comment sys/time.h
525@comment BSD
526@deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
99a20616
UD
527The @code{settimeofday} function sets the current calendar time in the
528system clock according to the arguments. As for @code{gettimeofday},
529the calendar time is represented as the elapsed time since the epoch.
530As for @code{gettimeofday}, time zone information is ignored if
531@var{tzp} is a null pointer.
28f540f4
RM
532
533You must be a privileged user in order to use @code{settimeofday}.
534
3566d33c
UD
535Some kernels automatically set the system clock from some source such as
536a hardware clock when they start up. Others, including Linux, place the
99a20616 537system clock in an ``invalid'' state (in which attempts to read the clock
3566d33c
UD
538fail). A call of @code{stime} removes the system clock from an invalid
539state, and system startup scripts typically run a program that calls
540@code{stime}.
541
542@code{settimeofday} causes a sudden jump forwards or backwards, which
543can cause a variety of problems in a system. Use @code{adjtime} (below)
544to make a smooth transition from one time to another by temporarily
545speeding up or slowing down the clock.
546
547With a Linux kernel, @code{adjtimex} does the same thing and can also
548make permanent changes to the speed of the system clock so it doesn't
549need to be corrected as often.
550
28f540f4
RM
551The return value is @code{0} on success and @code{-1} on failure. The
552following @code{errno} error conditions are defined for this function:
553
554@table @code
555@item EPERM
99a20616 556This process cannot set the clock because it is not privileged.
28f540f4
RM
557
558@item ENOSYS
559The operating system does not support setting time zone information, and
560@var{tzp} is not a null pointer.
561@end table
562@end deftypefun
563
3566d33c 564@c On Linux, GNU libc implements adjtime() as a call to adjtimex().
28f540f4
RM
565@comment sys/time.h
566@comment BSD
567@deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
568This function speeds up or slows down the system clock in order to make
99a20616
UD
569a gradual adjustment. This ensures that the calendar time reported by
570the system clock is always monotonically increasing, which might not
571happen if you simply set the clock.
28f540f4
RM
572
573The @var{delta} argument specifies a relative adjustment to be made to
99a20616
UD
574the clock time. If negative, the system clock is slowed down for a
575while until it has lost this much elapsed time. If positive, the system
576clock is speeded up for a while.
28f540f4
RM
577
578If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
579function returns information about any previous time adjustment that
580has not yet completed.
581
582This function is typically used to synchronize the clocks of computers
583in a local network. You must be a privileged user to use it.
3566d33c
UD
584
585With a Linux kernel, you can use the @code{adjtimex} function to
586permanently change the clock speed.
587
28f540f4
RM
588The return value is @code{0} on success and @code{-1} on failure. The
589following @code{errno} error condition is defined for this function:
590
591@table @code
592@item EPERM
593You do not have privilege to set the time.
594@end table
595@end deftypefun
596
597@strong{Portability Note:} The @code{gettimeofday}, @code{settimeofday},
01cdeca0 598and @code{adjtime} functions are derived from BSD.
28f540f4
RM
599
600
3566d33c
UD
601Symbols for the following function are declared in @file{sys/timex.h}.
602
603@comment sys/timex.h
604@comment GNU
605@deftypefun int adjtimex (struct timex *@var{timex})
606
607@code{adjtimex} is functionally identical to @code{ntp_adjtime}.
608@xref{High Accuracy Clock}.
609
610This function is present only with a Linux kernel.
611
612@end deftypefun
613
28f540f4
RM
614@node Broken-down Time
615@subsection Broken-down Time
616@cindex broken-down time
617@cindex calendar time and broken-down time
618
99a20616
UD
619Calendar time is represented by the usual GNU C library functions as an
620elapsed time since a fixed base calendar time. This is convenient for
621computation, but has no relation to the way people normally think of
622calendar time. By contrast, @dfn{broken-down time} is a binary
623representation of calendar time separated into year, month, day, and so
624on. Broken-down time values are not useful for calculations, but they
625are useful for printing human readable time information.
28f540f4 626
3566d33c 627A broken-down time value is always relative to a choice of time
99a20616 628zone, and it also indicates which time zone that is.
28f540f4
RM
629
630The symbols in this section are declared in the header file @file{time.h}.
631
632@comment time.h
f65fd747 633@comment ISO
28f540f4
RM
634@deftp {Data Type} {struct tm}
635This is the data type used to represent a broken-down time. The structure
99a20616 636contains at least the following members, which can appear in any order.
28f540f4
RM
637
638@table @code
639@item int tm_sec
99a20616
UD
640This is the number of full seconds since the top of the minute (normally
641in the range @code{0} through @code{59}, but the actual upper limit is
642@code{60}, to allow for leap seconds if leap second support is
643available).
28f540f4
RM
644@cindex leap second
645
646@item int tm_min
99a20616
UD
647This is the number of full minutes since the top of the hour (in the
648range @code{0} through @code{59}).
28f540f4
RM
649
650@item int tm_hour
99a20616
UD
651This is the number of full hours past midnight (in the range @code{0} through
652@code{23}).
28f540f4
RM
653
654@item int tm_mday
99a20616
UD
655This is the ordinal day of the month (in the range @code{1} through @code{31}).
656Watch out for this one! As the only ordinal number in the structure, it is
657inconsistent with the rest of the structure.
28f540f4
RM
658
659@item int tm_mon
99a20616
UD
660This is the number of full calendar months since the beginning of the
661year (in the range @code{0} through @code{11}). Watch out for this one!
662People usually use ordinal numbers for month-of-year (where January = 1).
28f540f4
RM
663
664@item int tm_year
99a20616 665This is the number of full calendar years since 1900.
28f540f4
RM
666
667@item int tm_wday
99a20616
UD
668This is the number of full days since Sunday (in the range @code{0} through
669@code{6}).
28f540f4
RM
670
671@item int tm_yday
99a20616
UD
672This is the number of full days since the beginning of the year (in the
673range @code{0} through @code{365}).
28f540f4
RM
674
675@item int tm_isdst
676@cindex Daylight Saving Time
677@cindex summer time
678This is a flag that indicates whether Daylight Saving Time is (or was, or
679will be) in effect at the time described. The value is positive if
680Daylight Saving Time is in effect, zero if it is not, and negative if the
681information is not available.
682
683@item long int tm_gmtoff
684This field describes the time zone that was used to compute this
f0f1bf85
UD
685broken-down time value, including any adjustment for daylight saving; it
686is the number of seconds that you must add to UTC to get local time.
687You can also think of this as the number of seconds east of UTC. For
688example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
689The @code{tm_gmtoff} field is derived from BSD and is a GNU library
f65fd747 690extension; it is not visible in a strict @w{ISO C} environment.
28f540f4
RM
691
692@item const char *tm_zone
f0f1bf85
UD
693This field is the name for the time zone that was used to compute this
694broken-down time value. Like @code{tm_gmtoff}, this field is a BSD and
f65fd747 695GNU extension, and is not visible in a strict @w{ISO C} environment.
28f540f4
RM
696@end table
697@end deftp
698
99a20616 699
28f540f4 700@comment time.h
f65fd747 701@comment ISO
28f540f4 702@deftypefun {struct tm *} localtime (const time_t *@var{time})
3566d33c 703The @code{localtime} function converts the simple time pointed to by
28f540f4
RM
704@var{time} to broken-down time representation, expressed relative to the
705user's specified time zone.
706
707The return value is a pointer to a static broken-down time structure, which
60092701
RM
708might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
709or @code{localtime}. (But no other library function overwrites the contents
710of this object.)
28f540f4 711
fe0ec73e
UD
712The return value is the null pointer if @var{time} cannot be represented
713as a broken-down time; typically this is because the year cannot fit into
714an @code{int}.
715
28f540f4
RM
716Calling @code{localtime} has one other effect: it sets the variable
717@code{tzname} with information about the current time zone. @xref{Time
718Zone Functions}.
719@end deftypefun
720
0413b54c
UD
721Using the @code{localtime} function is a big problem in multi-threaded
722programs. The result is returned in a static buffer and this is used in
76c23bac 723all threads. POSIX.1c introduced a variant of this function.
0413b54c
UD
724
725@comment time.h
726@comment POSIX.1c
727@deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
728The @code{localtime_r} function works just like the @code{localtime}
3566d33c 729function. It takes a pointer to a variable containing a simple time
0413b54c
UD
730and converts it to the broken-down time format.
731
732But the result is not placed in a static buffer. Instead it is placed
733in the object of type @code{struct tm} to which the parameter
734@var{resultp} points.
735
736If the conversion is successful the function returns a pointer to the
737object the result was written into, i.e., it returns @var{resultp}.
738@end deftypefun
739
740
28f540f4 741@comment time.h
f65fd747 742@comment ISO
28f540f4
RM
743@deftypefun {struct tm *} gmtime (const time_t *@var{time})
744This function is similar to @code{localtime}, except that the broken-down
3566d33c
UD
745time is expressed as Coordinated Universal Time (UTC) (formerly called
746Greenwich Mean Time (GMT)) rather than relative to a local time zone.
28f540f4 747
28f540f4
RM
748@end deftypefun
749
0413b54c 750As for the @code{localtime} function we have the problem that the result
f2ea0f5b 751is placed in a static variable. POSIX.1c also provides a replacement for
0413b54c
UD
752@code{gmtime}.
753
754@comment time.h
755@comment POSIX.1c
756@deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
757This function is similar to @code{localtime_r}, except that it converts
758just like @code{gmtime} the given time as Coordinated Universal Time.
759
760If the conversion is successful the function returns a pointer to the
761object the result was written into, i.e., it returns @var{resultp}.
762@end deftypefun
763
764
28f540f4 765@comment time.h
f65fd747 766@comment ISO
28f540f4
RM
767@deftypefun time_t mktime (struct tm *@var{brokentime})
768The @code{mktime} function is used to convert a broken-down time structure
3566d33c 769to a simple time representation. It also ``normalizes'' the contents of
28f540f4
RM
770the broken-down time structure, by filling in the day of week and day of
771year based on the other date and time components.
772
773The @code{mktime} function ignores the specified contents of the
774@code{tm_wday} and @code{tm_yday} members of the broken-down time
3566d33c 775structure. It uses the values of the other components to determine the
28f540f4 776calendar time; it's permissible for these components to have
76c23bac 777unnormalized values outside their normal ranges. The last thing that
28f540f4
RM
778@code{mktime} does is adjust the components of the @var{brokentime}
779structure (including the @code{tm_wday} and @code{tm_yday}).
780
3566d33c 781If the specified broken-down time cannot be represented as a simple time,
28f540f4
RM
782@code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
783the contents of @var{brokentime}.
784
785Calling @code{mktime} also sets the variable @code{tzname} with
786information about the current time zone. @xref{Time Zone Functions}.
787@end deftypefun
788
3566d33c
UD
789@comment time.h
790@comment ???
791@deftypefun time_t timelocal (struct tm *@var{brokentime})
792
793@code{timelocal} is functionally identical to @code{mktime}, but more
794mnemonically named. Note that it is the inverse of the @code{localtime}
795function.
796
797@strong{Portability note:} @code{mktime} is essentially universally
798available. @code{timelocal} is rather rare.
799
800@end deftypefun
801
802@comment time.h
803@comment ???
804@deftypefun time_t timegm (struct tm *@var{brokentime})
805
806@code{timegm} is functionally identical to @code{mktime} except it
807always takes the input values to be Coordinated Universal Time (UTC)
808regardless of any local time zone setting.
809
810Note that @code{timegm} is the inverse of @code{gmtime}.
811
812@strong{Portability note:} @code{mktime} is essentially universally
813available. @code{timegm} is rather rare. For the most portable
814conversion from a UTC broken-down time to a simple time, set
815the @code{TZ} environment variable to UTC, call @code{mktime}, then set
816@code{TZ} back.
817
818@end deftypefun
819
820
821
822@node High Accuracy Clock
823@subsection High Accuracy Clock
824
825@cindex time, high precision
826@cindex clock, high accuracy
827@pindex sys/timex.h
828@c On Linux, GNU libc implements ntp_gettime() and npt_adjtime() as calls
829@c to adjtimex().
830The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
831interface to monitor and manipulate the system clock to maintain high
832accuracy time. For example, you can fine tune the speed of the clock
833or synchronize it with another time source.
834
835A typical use of these functions is by a server implementing the Network
836Time Protocol to synchronize the clocks of multiple systems and high
837precision clocks.
838
839These functions are declared in @file{sys/timex.h}.
840
841@tindex struct ntptimeval
842@deftp {Data Type} {struct ntptimeval}
99a20616
UD
843This structure is used for information about the system clock. It
844contains the following members:
3566d33c
UD
845@table @code
846@item struct timeval time
99a20616
UD
847This is the current calendar time, expressed as the elapsed time since
848the epoch. The @code{struct timeval} data type is described in
849@ref{Elapsed Time}.
3566d33c
UD
850
851@item long int maxerror
852This is the maximum error, measured in microseconds. Unless updated
853via @code{ntp_adjtime} periodically, this value will reach some
854platform-specific maximum value.
855
856@item long int esterror
857This is the estimated error, measured in microseconds. This value can
858be set by @code{ntp_adjtime} to indicate the estimated offset of the
99a20616 859system clock from the true calendar time.
3566d33c
UD
860@end table
861@end deftp
862
863@comment sys/timex.h
864@comment GNU
865@deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
866The @code{ntp_gettime} function sets the structure pointed to by
867@var{tptr} to current values. The elements of the structure afterwards
868contain the values the timer implementation in the kernel assumes. They
869might or might not be correct. If they are not a @code{ntp_adjtime}
870call is necessary.
871
872The return value is @code{0} on success and other values on failure. The
873following @code{errno} error conditions are defined for this function:
874
875@table @code
876@item TIME_ERROR
877The precision clock model is not properly set up at the moment, thus the
878clock must be considered unsynchronized, and the values should be
879treated with care.
880@end table
881@end deftypefun
882
883@tindex struct timex
884@deftp {Data Type} {struct timex}
885This structure is used to control and monitor the system clock. It
886contains the following members:
887@table @code
888@item unsigned int modes
889This variable controls whether and which values are set. Several
890symbolic constants have to be combined with @emph{binary or} to specify
891the effective mode. These constants start with @code{MOD_}.
892
893@item long int offset
99a20616
UD
894This value indicates the current offset of the system clock from the true
895calendar time. The value is given in microseconds. If bit
896@code{MOD_OFFSET} is set in @code{modes}, the offset (and possibly other
897dependent values) can be set. The offset's absolute value must not
898exceed @code{MAXPHASE}.
3566d33c
UD
899
900
901@item long int frequency
99a20616
UD
902This value indicates the difference in frequency between the true
903calendar time and the system clock. The value is expressed as scaled
904PPM (parts per million, 0.0001%). The scaling is @code{1 <<
905SHIFT_USEC}. The value can be set with bit @code{MOD_FREQUENCY}, but
906the absolute value must not exceed @code{MAXFREQ}.
3566d33c
UD
907
908@item long int maxerror
909This is the maximum error, measured in microseconds. A new value can be
910set using bit @code{MOD_MAXERROR}. Unless updated via
911@code{ntp_adjtime} periodically, this value will increase steadily
912and reach some platform-specific maximum value.
913
914@item long int esterror
915This is the estimated error, measured in microseconds. This value can
916be set using bit @code{MOD_ESTERROR}.
917
918@item int status
919This variable reflects the various states of the clock machinery. There
920are symbolic constants for the significant bits, starting with
921@code{STA_}. Some of these flags can be updated using the
922@code{MOD_STATUS} bit.
923
924@item long int constant
925This value represents the bandwidth or stiffness of the PLL (phase
926locked loop) implemented in the kernel. The value can be changed using
927bit @code{MOD_TIMECONST}.
928
929@item long int precision
930This value represents the accuracy or the maximum error when reading the
931system clock. The value is expressed in microseconds.
932
933@item long int tolerance
934This value represents the maximum frequency error of the system clock in
935scaled PPM. This value is used to increase the @code{maxerror} every
936second.
937
938@item struct timeval time
99a20616 939The current calendar time.
3566d33c
UD
940
941@item long int tick
99a20616 942The elapsed time between clock ticks in microseconds. A clock tick is a
3566d33c
UD
943periodic timer interrupt on which the system clock is based.
944
945@item long int ppsfreq
946This is the first of a few optional variables that are present only if
947the system clock can use a PPS (pulse per second) signal to discipline
99a20616
UD
948the system clock. The value is expressed in scaled PPM and it denotes
949the difference in frequency between the system clock and the PPS signal.
3566d33c
UD
950
951@item long int jitter
952This value expresses a median filtered average of the PPS signal's
953dispersion in microseconds.
954
955@item int shift
956This value is a binary exponent for the duration of the PPS calibration
957interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
958
959@item long int stabil
960This value represents the median filtered dispersion of the PPS
961frequency in scaled PPM.
962
963@item long int jitcnt
964This counter represents the number of pulses where the jitter exceeded
965the allowed maximum @code{MAXTIME}.
966
967@item long int calcnt
968This counter reflects the number of successful calibration intervals.
969
970@item long int errcnt
971This counter represents the number of calibration errors (caused by
972large offsets or jitter).
973
974@item long int stbcnt
975This counter denotes the number of of calibrations where the stability
976exceeded the threshold.
977@end table
978@end deftp
979
980@comment sys/timex.h
981@comment GNU
982@deftypefun int ntp_adjtime (struct timex *@var{tptr})
983The @code{ntp_adjtime} function sets the structure specified by
984@var{tptr} to current values.
985
986In addition, @code{ntp_adjtime} updates some settings to match what you
987pass to it in *@var{tptr}. Use the @code{modes} element of *@var{tptr}
988to select what settings to update. You can set @code{offset},
989@code{freq}, @code{maxerror}, @code{esterror}, @code{status},
990@code{constant}, and @code{tick}.
991
992@code{modes} = zero means set nothing.
993
994Only the superuser can update settings.
995
996@c On Linux, ntp_adjtime() also does the adjtime() function if you set
997@c modes = ADJ_OFFSET_SINGLESHOT (in fact, that is how GNU libc implements
998@c adjtime()). But this should be considered an internal function because
999@c it's so inconsistent with the rest of what ntp_adjtime() does and is
1000@c forced in an ugly way into the struct timex. So we don't document it
1001@c and instead document adjtime() as the way to achieve the function.
1002
1003The return value is @code{0} on success and other values on failure. The
1004following @code{errno} error conditions are defined for this function:
1005
1006@table @code
1007@item TIME_ERROR
1008The high accuracy clock model is not properly set up at the moment, thus the
1009clock must be considered unsynchronized, and the values should be
1010treated with care. Another reason could be that the specified new values
1011are not allowed.
1012
1013@item EPERM
1014The process specified a settings update, but is not superuser.
1015
1016@end table
1017
1018For more details see RFC1305 (Network Time Protocol, Version 3) and
1019related documents.
1020
1021@strong{Portability note:} Early versions of the GNU C library did not
1022have this function but did have the synonymous @code{adjtimex}.
1023
1024@end deftypefun
1025
1026
99a20616
UD
1027@node Formatting Calendar Time
1028@subsection Formatting Calendar Time
28f540f4 1029
99a20616
UD
1030The functions described in this section format calendar time values as
1031strings. These functions are declared in the header file @file{time.h}.
28f540f4
RM
1032@pindex time.h
1033
1034@comment time.h
f65fd747 1035@comment ISO
28f540f4
RM
1036@deftypefun {char *} asctime (const struct tm *@var{brokentime})
1037The @code{asctime} function converts the broken-down time value that
1038@var{brokentime} points to into a string in a standard format:
1039
1040@smallexample
1041"Tue May 21 13:46:22 1991\n"
1042@end smallexample
1043
1044The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
1045@samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
1046
1047The abbreviations for the months are: @samp{Jan}, @samp{Feb},
1048@samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
1049@samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
1050
1051The return value points to a statically allocated string, which might be
60092701 1052overwritten by subsequent calls to @code{asctime} or @code{ctime}.
28f540f4
RM
1053(But no other library function overwrites the contents of this
1054string.)
1055@end deftypefun
1056
0413b54c
UD
1057@comment time.h
1058@comment POSIX.1c
1059@deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
1060This function is similar to @code{asctime} but instead of placing the
1061result in a static buffer it writes the string in the buffer pointed to
76c23bac
UD
1062by the parameter @var{buffer}. This buffer should have room
1063for at least 26 bytes, including the terminating null.
0413b54c
UD
1064
1065If no error occurred the function returns a pointer to the string the
1066result was written into, i.e., it returns @var{buffer}. Otherwise
1067return @code{NULL}.
1068@end deftypefun
1069
1070
28f540f4 1071@comment time.h
f65fd747 1072@comment ISO
28f540f4 1073@deftypefun {char *} ctime (const time_t *@var{time})
99a20616
UD
1074The @code{ctime} function is similar to @code{asctime}, except that you
1075specify the calendar time argument as a @code{time_t} simple time value
1076rather than in broken-down local time format. It is equivalent to
28f540f4
RM
1077
1078@smallexample
1079asctime (localtime (@var{time}))
1080@end smallexample
1081
1082@code{ctime} sets the variable @code{tzname}, because @code{localtime}
1083does so. @xref{Time Zone Functions}.
1084@end deftypefun
1085
0413b54c
UD
1086@comment time.h
1087@comment POSIX.1c
1088@deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
99a20616
UD
1089This function is similar to @code{ctime}, but places the result in the
1090string pointed to by @var{buffer}. It is equivalent to (written using
1091gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
0413b54c
UD
1092
1093@smallexample
1094(@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
1095@end smallexample
1096
1097If no error occurred the function returns a pointer to the string the
1098result was written into, i.e., it returns @var{buffer}. Otherwise
1099return @code{NULL}.
1100@end deftypefun
1101
1102
28f540f4 1103@comment time.h
f65fd747 1104@comment ISO
28f540f4
RM
1105@deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
1106This function is similar to the @code{sprintf} function (@pxref{Formatted
1107Input}), but the conversion specifications that can appear in the format
1108template @var{template} are specialized for printing components of the date
1109and time @var{brokentime} according to the locale currently specified for
1110time conversion (@pxref{Locales}).
1111
1112Ordinary characters appearing in the @var{template} are copied to the
1113output string @var{s}; this can include multibyte character sequences.
ec4b0518 1114Conversion specifiers are introduced by a @samp{%} character, followed
a2b08ee5
UD
1115by an optional flag which can be one of the following. These flags
1116are all GNU extensions. The first three affect only the output of
1117numbers:
2de99474
UD
1118
1119@table @code
1120@item _
1121The number is padded with spaces.
1122
1123@item -
1124The number is not padded at all.
860d3729
UD
1125
1126@item 0
7e3be507 1127The number is padded with zeros even if the format specifies padding
860d3729 1128with spaces.
7e3be507
UD
1129
1130@item ^
1131The output uses uppercase characters, but only if this is possible
1132(@pxref{Case Conversion}).
2de99474
UD
1133@end table
1134
ec4b0518
UD
1135The default action is to pad the number with zeros to keep it a constant
1136width. Numbers that do not have a range indicated below are never
1137padded, since there is no natural width for them.
1138
860d3729
UD
1139Following the flag an optional specification of the width is possible.
1140This is specified in decimal notation. If the natural size of the
5b826692 1141output is of the field has less than the specified number of characters,
860d3729
UD
1142the result is written right adjusted and space padded to the given
1143size.
1144
1145An optional modifier can follow the optional flag and width
ba737b94
UD
1146specification. The modifiers, which were first standardized by
1147POSIX.2-1992 and by @w{ISO C99}, are:
ec4b0518
UD
1148
1149@table @code
1150@item E
1151Use the locale's alternate representation for date and time. This
1152modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
1153@code{%y} and @code{%Y} format specifiers. In a Japanese locale, for
1154example, @code{%Ex} might yield a date format based on the Japanese
1155Emperors' reigns.
1156
1157@item O
1158Use the locale's alternate numeric symbols for numbers. This modifier
1159applies only to numeric format specifiers.
1160@end table
1161
860d3729
UD
1162If the format supports the modifier but no alternate representation
1163is available, it is ignored.
ec4b0518
UD
1164
1165The conversion specifier ends with a format specifier taken from the
1166following list. The whole @samp{%} sequence is replaced in the output
1167string as follows:
28f540f4
RM
1168
1169@table @code
1170@item %a
1171The abbreviated weekday name according to the current locale.
1172
1173@item %A
1174The full weekday name according to the current locale.
1175
1176@item %b
1177The abbreviated month name according to the current locale.
1178
1179@item %B
1180The full month name according to the current locale.
1181
c093ea4f
UD
1182Using @code{%B} together with @code{%d} produces grammatically
1183incorrect results for some locales.
1184
28f540f4 1185@item %c
99a20616 1186The preferred calendar time representation for the current locale.
28f540f4 1187
2de99474 1188@item %C
ec4b0518
UD
1189The century of the year. This is equivalent to the greatest integer not
1190greater than the year divided by 100.
1191
ba737b94 1192This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
2de99474 1193
28f540f4 1194@item %d
ec4b0518 1195The day of the month as a decimal number (range @code{01} through @code{31}).
28f540f4 1196
2de99474
UD
1197@item %D
1198The date using the format @code{%m/%d/%y}.
1199
ba737b94 1200This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
2de99474 1201
ec4b0518 1202@item %e
2de99474 1203The day of the month like with @code{%d}, but padded with blank (range
ec4b0518
UD
1204@code{ 1} through @code{31}).
1205
ba737b94 1206This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
ec4b0518 1207
fe0ec73e
UD
1208@item %F
1209The date using the format @code{%Y-%m-%d}. This is the form specified
1210in the @w{ISO 8601} standard and is the preferred form for all uses.
1211
ba737b94 1212This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
fe0ec73e 1213
ec4b0518
UD
1214@item %g
1215The year corresponding to the ISO week number, but without the century
1216(range @code{00} through @code{99}). This has the same format and value
1217as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
1218to the previous or next year, that year is used instead.
1219
ba737b94 1220This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
ec4b0518
UD
1221
1222@item %G
1223The year corresponding to the ISO week number. This has the same format
1224and value as @code{%Y}, except that if the ISO week number (see
1225@code{%V}) belongs to the previous or next year, that year is used
1226instead.
2de99474 1227
ba737b94
UD
1228This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1229but was previously available as a GNU extension.
2de99474
UD
1230
1231@item %h
1232The abbreviated month name according to the current locale. The action
1233is the same as for @code{%b}.
1234
ba737b94 1235This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
2de99474 1236
28f540f4 1237@item %H
ec4b0518 1238The hour as a decimal number, using a 24-hour clock (range @code{00} through
28f540f4
RM
1239@code{23}).
1240
1241@item %I
ec4b0518 1242The hour as a decimal number, using a 12-hour clock (range @code{01} through
28f540f4
RM
1243@code{12}).
1244
1245@item %j
ec4b0518 1246The day of the year as a decimal number (range @code{001} through @code{366}).
28f540f4 1247
2de99474
UD
1248@item %k
1249The hour as a decimal number, using a 24-hour clock like @code{%H}, but
ec4b0518 1250padded with blank (range @code{ 0} through @code{23}).
2de99474
UD
1251
1252This format is a GNU extension.
1253
1254@item %l
1255The hour as a decimal number, using a 12-hour clock like @code{%I}, but
ec4b0518 1256padded with blank (range @code{ 1} through @code{12}).
2de99474
UD
1257
1258This format is a GNU extension.
1259
28f540f4 1260@item %m
ec4b0518 1261The month as a decimal number (range @code{01} through @code{12}).
28f540f4
RM
1262
1263@item %M
ec4b0518 1264The minute as a decimal number (range @code{00} through @code{59}).
28f540f4 1265
2de99474
UD
1266@item %n
1267A single @samp{\n} (newline) character.
1268
ba737b94 1269This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
2de99474 1270
28f540f4 1271@item %p
ec4b0518
UD
1272Either @samp{AM} or @samp{PM}, according to the given time value; or the
1273corresponding strings for the current locale. Noon is treated as
eabea972
UD
1274@samp{PM} and midnight as @samp{AM}. In most locales
1275@samp{AM}/@samp{PM} format is not supported, in such cases @code{"%p"}
1276yields an empty string.
28f540f4 1277
7e3be507
UD
1278@ignore
1279We currently have a problem with makeinfo. Write @samp{AM} and @samp{am}
1280both results in `am'. I.e., the difference in case is not visible anymore.
1281@end ignore
1282@item %P
1283Either @samp{am} or @samp{pm}, according to the given time value; or the
1284corresponding strings for the current locale, printed in lowercase
eabea972
UD
1285characters. Noon is treated as @samp{pm} and midnight as @samp{am}. In
1286most locales @samp{AM}/@samp{PM} format is not supported, in such cases
1287@code{"%P"} yields an empty string.
7e3be507 1288
ba737b94 1289This format is a GNU extension.
7e3be507 1290
2de99474 1291@item %r
99a20616 1292The complete calendar time using the AM/PM format of the current locale.
2de99474 1293
ba737b94
UD
1294This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1295In the POSIX locale, this format is equivalent to @code{%I:%M:%S %p}.
2de99474
UD
1296
1297@item %R
1298The hour and minute in decimal numbers using the format @code{%H:%M}.
1299
ba737b94
UD
1300This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1301but was previously available as a GNU extension.
2de99474
UD
1302
1303@item %s
ec4b0518
UD
1304The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1305Leap seconds are not counted unless leap second support is available.
2de99474
UD
1306
1307This format is a GNU extension.
1308
28f540f4 1309@item %S
e9dcb080 1310The seconds as a decimal number (range @code{00} through @code{60}).
28f540f4 1311
2de99474
UD
1312@item %t
1313A single @samp{\t} (tabulator) character.
1314
ba737b94 1315This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
2de99474
UD
1316
1317@item %T
99a20616 1318The time of day using decimal numbers using the format @code{%H:%M:%S}.
2de99474 1319
ba737b94 1320This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
ec4b0518
UD
1321
1322@item %u
1323The day of the week as a decimal number (range @code{1} through
1324@code{7}), Monday being @code{1}.
1325
ba737b94 1326This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
2de99474 1327
28f540f4 1328@item %U
ec4b0518
UD
1329The week number of the current year as a decimal number (range @code{00}
1330through @code{53}), starting with the first Sunday as the first day of
1331the first week. Days preceding the first Sunday in the year are
1332considered to be in week @code{00}.
7c713e28
RM
1333
1334@item %V
ec4b0518
UD
1335The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
1336through @code{53}). ISO weeks start with Monday and end with Sunday.
1337Week @code{01} of a year is the first week which has the majority of its
1338days in that year; this is equivalent to the week containing the year's
1339first Thursday, and it is also equivalent to the week containing January
13404. Week @code{01} of a year can contain days from the previous year.
1341The week before week @code{01} of a year is the last week (@code{52} or
1342@code{53}) of the previous year even if it contains days from the new
1343year.
1344
ba737b94 1345This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
28f540f4 1346
2de99474 1347@item %w
ec4b0518
UD
1348The day of the week as a decimal number (range @code{0} through
1349@code{6}), Sunday being @code{0}.
2de99474 1350
28f540f4 1351@item %W
ec4b0518
UD
1352The week number of the current year as a decimal number (range @code{00}
1353through @code{53}), starting with the first Monday as the first day of
1354the first week. All days preceding the first Monday in the year are
1355considered to be in week @code{00}.
28f540f4 1356
28f540f4 1357@item %x
99a20616 1358The preferred date representation for the current locale.
28f540f4
RM
1359
1360@item %X
99a20616 1361The preferred time of day representation for the current locale.
28f540f4
RM
1362
1363@item %y
ec4b0518
UD
1364The year without a century as a decimal number (range @code{00} through
1365@code{99}). This is equivalent to the year modulo 100.
28f540f4
RM
1366
1367@item %Y
ec4b0518
UD
1368The year as a decimal number, using the Gregorian calendar. Years
1369before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
28f540f4 1370
2de99474 1371@item %z
f0f1bf85
UD
1372@w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
1373@code{-0600} or @code{+0100}), or nothing if no time zone is
1374determinable.
2de99474 1375
ba737b94
UD
1376This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1377but was previously available as a GNU extension.
ec4b0518 1378
ba737b94 1379In the POSIX locale, a full @w{RFC 822} timestamp is generated by the format
e9dcb080 1380@w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
eeabe877 1381@w{@samp{"%a, %d %b %Y %T %z"}}).
e1350332 1382
28f540f4 1383@item %Z
ec4b0518 1384The time zone abbreviation (empty if the time zone can't be determined).
28f540f4
RM
1385
1386@item %%
1387A literal @samp{%} character.
1388@end table
1389
1390The @var{size} parameter can be used to specify the maximum number of
1391characters to be stored in the array @var{s}, including the terminating
1392null character. If the formatted time requires more than @var{size}
76c23bac
UD
1393characters, @code{strftime} returns zero and the contents of the array
1394@var{s} are undefined. Otherwise the return value indicates the
55c14926
UD
1395number of characters placed in the array @var{s}, not including the
1396terminating null character.
1397
1398@emph{Warning:} This convention for the return value which is prescribed
1399in @w{ISO C} can lead to problems in some situations. For certain
1400format strings and certain locales the output really can be the empty
1401string and this cannot be discovered by testing the return value only.
1402E.g., in most locales the AM/PM time format is not supported (most of
1403the world uses the 24 hour time representation). In such locales
1404@code{"%p"} will return the empty string, i.e., the return value is
1405zero. To detect situations like this something similar to the following
1406code should be used:
1407
1408@smallexample
1409buf[0] = '\1';
1410len = strftime (buf, bufsize, format, tp);
1411if (len == 0 && buf[0] != '\0')
1412 @{
1413 /* Something went wrong in the strftime call. */
1414 @dots{}
1415 @}
1416@end smallexample
28f540f4
RM
1417
1418If @var{s} is a null pointer, @code{strftime} does not actually write
1419anything, but instead returns the number of characters it would have written.
1420
860d3729
UD
1421According to POSIX.1 every call to @code{strftime} implies a call to
1422@code{tzset}. So the contents of the environment variable @code{TZ}
1423is examined before any output is produced.
1424
28f540f4
RM
1425For an example of @code{strftime}, see @ref{Time Functions Example}.
1426@end deftypefun
1427
d64b6ad0
UD
1428@comment time.h
1429@comment ISO/Amend1
1430@deftypefun size_t wcsftime (wchar_t *@var{s}, size_t @var{size}, const wchar_t *@var{template}, const struct tm *@var{brokentime})
1431The @code{wcsftime} function is equivalent to the @code{strftime}
76c23bac 1432function with the difference that it operates on wide character
d64b6ad0
UD
1433strings. The buffer where the result is stored, pointed to by @var{s},
1434must be an array of wide characters. The parameter @var{size} which
1435specifies the size of the output buffer gives the number of wide
1436character, not the number of bytes.
1437
1438Also the format string @var{template} is a wide character string. Since
1439all characters needed to specify the format string are in the basic
76c23bac 1440character set it is portably possible to write format strings in the C
95fdc6a0 1441source code using the @code{L"@dots{}"} notation. The parameter
d64b6ad0
UD
1442@var{brokentime} has the same meaning as in the @code{strftime} call.
1443
1444The @code{wcsftime} function supports the same flags, modifiers, and
1445format specifiers as the @code{strftime} function.
1446
1447The return value of @code{wcsftime} is the number of wide characters
1448stored in @code{s}. When more characters would have to be written than
1449can be placed in the buffer @var{s} the return value is zero, with the
1450same problems indicated in the @code{strftime} documentation.
1451@end deftypefun
1452
e9dcb080
UD
1453@node Parsing Date and Time
1454@subsection Convert textual time and date information back
1455
1456The @w{ISO C} standard does not specify any functions which can convert
1457the output of the @code{strftime} function back into a binary format.
76c23bac
UD
1458This led to a variety of more-or-less successful implementations with
1459different interfaces over the years. Then the Unix standard was
1460extended by the addition of two functions: @code{strptime} and
1461@code{getdate}. Both have strange interfaces but at least they are
1462widely available.
e9dcb080
UD
1463
1464@menu
1465* Low-Level Time String Parsing:: Interpret string according to given format.
1466* General Time String Parsing:: User-friendly function to parse data and
1467 time strings.
1468@end menu
1469
1470@node Low-Level Time String Parsing
1471@subsubsection Interpret string according to given format
1472
32c075e1 1473he first function is rather low-level. It is nevertheless frequently
76c23bac
UD
1474used in software since it is better known. Its interface and
1475implementation are heavily influenced by the @code{getdate} function,
1476which is defined and implemented in terms of calls to @code{strptime}.
e9dcb080
UD
1477
1478@comment time.h
1479@comment XPG4
1480@deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1481The @code{strptime} function parses the input string @var{s} according
76c23bac 1482to the format string @var{fmt} and stores its results in the
e9dcb080
UD
1483structure @var{tp}.
1484
76c23bac
UD
1485The input string could be generated by a @code{strftime} call or
1486obtained any other way. It does not need to be in a human-recognizable
1487format; e.g. a date passed as @code{"02:1999:9"} is acceptable, even
1488though it is ambiguous without context. As long as the format string
1489@var{fmt} matches the input string the function will succeed.
e9dcb080 1490
45e0579f
UD
1491The user has to make sure, though, that the input can be parsed in a
1492unambiguous way. The string @code{"1999112"} can be parsed using the
1493format @code{"%Y%m%d"} as 1999-1-12, 1999-11-2, or even 19991-1-2. It
1494is necessary to add appropriate separators to reliably get results.
1495
e9dcb080 1496The format string consists of the same components as the format string
76c23bac 1497of the @code{strftime} function. The only difference is that the flags
e9dcb080
UD
1498@code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1499@comment Is this really the intention? --drepper
76c23bac
UD
1500Several of the distinct formats of @code{strftime} do the same work in
1501@code{strptime} since differences like case of the input do not matter.
1502For reasons of symmetry all formats are supported, though.
e9dcb080
UD
1503
1504The modifiers @code{E} and @code{O} are also allowed everywhere the
1505@code{strftime} function allows them.
1506
1507The formats are:
1508
1509@table @code
1510@item %a
1511@itemx %A
1512The weekday name according to the current locale, in abbreviated form or
1513the full name.
1514
1515@item %b
1516@itemx %B
1517@itemx %h
1518The month name according to the current locale, in abbreviated form or
1519the full name.
1520
1521@item %c
1522The date and time representation for the current locale.
1523
1524@item %Ec
1525Like @code{%c} but the locale's alternative date and time format is used.
1526
1527@item %C
1528The century of the year.
1529
1530It makes sense to use this format only if the format string also
1531contains the @code{%y} format.
1532
1533@item %EC
1534The locale's representation of the period.
1535
76c23bac
UD
1536Unlike @code{%C} it sometimes makes sense to use this format since some
1537cultures represent years relative to the beginning of eras instead of
1538using the Gregorian years.
e9dcb080
UD
1539
1540@item %d
1541@item %e
1542The day of the month as a decimal number (range @code{1} through @code{31}).
1543Leading zeroes are permitted but not required.
1544
1545@item %Od
1546@itemx %Oe
76c23bac 1547Same as @code{%d} but using the locale's alternative numeric symbols.
e9dcb080
UD
1548
1549Leading zeroes are permitted but not required.
1550
1551@item %D
76c23bac 1552Equivalent to @code{%m/%d/%y}.
e9dcb080
UD
1553
1554@item %F
76c23bac 1555Equivalent to @code{%Y-%m-%d}, which is the @w{ISO 8601} date
e9dcb080
UD
1556format.
1557
ec751a23 1558This is a GNU extension following an @w{ISO C99} extension to
e9dcb080
UD
1559@code{strftime}.
1560
1561@item %g
1562The year corresponding to the ISO week number, but without the century
1563(range @code{00} through @code{99}).
1564
76c23bac 1565@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1566recognized, input is consumed but no field in @var{tm} is set.
1567
1568This format is a GNU extension following a GNU extension of @code{strftime}.
1569
1570@item %G
1571The year corresponding to the ISO week number.
1572
76c23bac 1573@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1574recognized, input is consumed but no field in @var{tm} is set.
1575
1576This format is a GNU extension following a GNU extension of @code{strftime}.
1577
1578@item %H
1579@itemx %k
1580The hour as a decimal number, using a 24-hour clock (range @code{00} through
1581@code{23}).
1582
1583@code{%k} is a GNU extension following a GNU extension of @code{strftime}.
1584
1585@item %OH
76c23bac 1586Same as @code{%H} but using the locale's alternative numeric symbols.
e9dcb080
UD
1587
1588@item %I
1589@itemx %l
1590The hour as a decimal number, using a 12-hour clock (range @code{01} through
1591@code{12}).
1592
1593@code{%l} is a GNU extension following a GNU extension of @code{strftime}.
1594
1595@item %OI
76c23bac 1596Same as @code{%I} but using the locale's alternative numeric symbols.
e9dcb080
UD
1597
1598@item %j
1599The day of the year as a decimal number (range @code{1} through @code{366}).
1600
1601Leading zeroes are permitted but not required.
1602
1603@item %m
1604The month as a decimal number (range @code{1} through @code{12}).
1605
1606Leading zeroes are permitted but not required.
1607
1608@item %Om
76c23bac 1609Same as @code{%m} but using the locale's alternative numeric symbols.
e9dcb080
UD
1610
1611@item %M
1612The minute as a decimal number (range @code{0} through @code{59}).
1613
1614Leading zeroes are permitted but not required.
1615
1616@item %OM
76c23bac 1617Same as @code{%M} but using the locale's alternative numeric symbols.
e9dcb080
UD
1618
1619@item %n
1620@itemx %t
1621Matches any white space.
1622
1623@item %p
1624@item %P
1625The locale-dependent equivalent to @samp{AM} or @samp{PM}.
1626
1627This format is not useful unless @code{%I} or @code{%l} is also used.
1628Another complication is that the locale might not define these values at
1629all and therefore the conversion fails.
1630
1631@code{%P} is a GNU extension following a GNU extension to @code{strftime}.
1632
1633@item %r
1634The complete time using the AM/PM format of the current locale.
1635
1636A complication is that the locale might not define this format at all
1637and therefore the conversion fails.
1638
1639@item %R
1640The hour and minute in decimal numbers using the format @code{%H:%M}.
1641
1642@code{%R} is a GNU extension following a GNU extension to @code{strftime}.
1643
1644@item %s
1645The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1646Leap seconds are not counted unless leap second support is available.
1647
1648@code{%s} is a GNU extension following a GNU extension to @code{strftime}.
1649
1650@item %S
99a20616 1651The seconds as a decimal number (range @code{0} through @code{60}).
e9dcb080
UD
1652
1653Leading zeroes are permitted but not required.
1654
99a20616
UD
1655@strong{Note:} The Unix specification says the upper bound on this value
1656is @code{61}, a result of a decision to allow double leap seconds. You
1657will not see the value @code{61} because no minute has more than one
1658leap second, but the myth persists.
e9dcb080
UD
1659
1660@item %OS
76c23bac 1661Same as @code{%S} but using the locale's alternative numeric symbols.
e9dcb080
UD
1662
1663@item %T
1664Equivalent to the use of @code{%H:%M:%S} in this place.
1665
1666@item %u
1667The day of the week as a decimal number (range @code{1} through
1668@code{7}), Monday being @code{1}.
1669
1670Leading zeroes are permitted but not required.
1671
76c23bac 1672@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1673recognized, input is consumed but no field in @var{tm} is set.
1674
1675@item %U
1676The week number of the current year as a decimal number (range @code{0}
1677through @code{53}).
1678
1679Leading zeroes are permitted but not required.
1680
1681@item %OU
76c23bac 1682Same as @code{%U} but using the locale's alternative numeric symbols.
e9dcb080
UD
1683
1684@item %V
1685The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
1686through @code{53}).
1687
1688Leading zeroes are permitted but not required.
1689
76c23bac 1690@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1691recognized, input is consumed but no field in @var{tm} is set.
1692
1693@item %w
1694The day of the week as a decimal number (range @code{0} through
1695@code{6}), Sunday being @code{0}.
1696
1697Leading zeroes are permitted but not required.
1698
76c23bac 1699@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1700recognized, input is consumed but no field in @var{tm} is set.
1701
1702@item %Ow
76c23bac 1703Same as @code{%w} but using the locale's alternative numeric symbols.
e9dcb080
UD
1704
1705@item %W
1706The week number of the current year as a decimal number (range @code{0}
1707through @code{53}).
1708
1709Leading zeroes are permitted but not required.
1710
76c23bac 1711@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1712recognized, input is consumed but no field in @var{tm} is set.
1713
1714@item %OW
76c23bac 1715Same as @code{%W} but using the locale's alternative numeric symbols.
e9dcb080
UD
1716
1717@item %x
1718The date using the locale's date format.
1719
1720@item %Ex
1721Like @code{%x} but the locale's alternative data representation is used.
1722
1723@item %X
1724The time using the locale's time format.
1725
1726@item %EX
1727Like @code{%X} but the locale's alternative time representation is used.
1728
1729@item %y
1730The year without a century as a decimal number (range @code{0} through
1731@code{99}).
1732
1733Leading zeroes are permitted but not required.
1734
76c23bac 1735Note that it is questionable to use this format without
e9dcb080
UD
1736the @code{%C} format. The @code{strptime} function does regard input
1737values in the range @math{68} to @math{99} as the years @math{1969} to
1738@math{1999} and the values @math{0} to @math{68} as the years
1739@math{2000} to @math{2068}. But maybe this heuristic fails for some
1740input data.
1741
1742Therefore it is best to avoid @code{%y} completely and use @code{%Y}
1743instead.
1744
1745@item %Ey
1746The offset from @code{%EC} in the locale's alternative representation.
1747
1748@item %Oy
1749The offset of the year (from @code{%C}) using the locale's alternative
1750numeric symbols.
1751
1752@item %Y
1753The year as a decimal number, using the Gregorian calendar.
1754
1755@item %EY
1756The full alternative year representation.
1757
1758@item %z
107d41a9 1759The offset from GMT in @w{ISO 8601}/RFC822 format.
e9dcb080
UD
1760
1761@item %Z
1762The timezone name.
1763
76c23bac 1764@emph{Note:} Currently, this is not fully implemented. The format is
e9dcb080
UD
1765recognized, input is consumed but no field in @var{tm} is set.
1766
1767@item %%
1768A literal @samp{%} character.
1769@end table
1770
1771All other characters in the format string must have a matching character
1772in the input string. Exceptions are white spaces in the input string
05957bbd
UD
1773which can match zero or more whitespace characters in the format string.
1774
1775@strong{Portability Note:} The XPG standard advises applications to use
1776at least one whitespace character (as specified by @code{isspace}) or
1777other non-alphanumeric characters between any two conversion
1778specifications. The @w{GNU C Library} does not have this limitation but
1779other libraries might have trouble parsing formats like
1780@code{"%d%m%Y%H%M%S"}.
e9dcb080
UD
1781
1782The @code{strptime} function processes the input string from right to
1783left. Each of the three possible input elements (white space, literal,
1784or format) are handled one after the other. If the input cannot be
1785matched to the format string the function stops. The remainder of the
1786format and input strings are not processed.
1787
76c23bac
UD
1788The function returns a pointer to the first character it was unable to
1789process. If the input string contains more characters than required by
1790the format string the return value points right after the last consumed
1791input character. If the whole input string is consumed the return value
1792points to the @code{NULL} byte at the end of the string. If an error
32c075e1 1793occurs, i.e. @code{strptime} fails to match all of the format string,
76c23bac 1794the function returns @code{NULL}.
e9dcb080
UD
1795@end deftypefun
1796
76c23bac
UD
1797The specification of the function in the XPG standard is rather vague,
1798leaving out a few important pieces of information. Most importantly, it
e9dcb080 1799does not specify what happens to those elements of @var{tm} which are
76c23bac 1800not directly initialized by the different formats. The
e9dcb080
UD
1801implementations on different Unix systems vary here.
1802
1803The GNU libc implementation does not touch those fields which are not
1804directly initialized. Exceptions are the @code{tm_wday} and
76c23bac 1805@code{tm_yday} elements, which are recomputed if any of the year, month,
e9dcb080
UD
1806or date elements changed. This has two implications:
1807
1808@itemize @bullet
1809@item
76c23bac
UD
1810Before calling the @code{strptime} function for a new input string, you
1811should prepare the @var{tm} structure you pass. Normally this will mean
1812initializing all values are to zero. Alternatively, you can set all
1813fields to values like @code{INT_MAX}, allowing you to determine which
1814elements were set by the function call. Zero does not work here since
1815it is a valid value for many of the fields.
1816
1817Careful initialization is necessary if you want to find out whether a
e9dcb080
UD
1818certain field in @var{tm} was initialized by the function call.
1819
1820@item
76c23bac
UD
1821You can construct a @code{struct tm} value with several consecutive
1822@code{strptime} calls. A useful application of this is e.g. the parsing
1823of two separate strings, one containing date information and the other
1824time information. By parsing one after the other without clearing the
1825structure in-between, you can construct a complete broken-down time.
e9dcb080
UD
1826@end itemize
1827
1828The following example shows a function which parses a string which is
76c23bac 1829contains the date information in either US style or @w{ISO 8601} form:
e9dcb080
UD
1830
1831@smallexample
1832const char *
1833parse_date (const char *input, struct tm *tm)
1834@{
1835 const char *cp;
1836
1837 /* @r{First clear the result structure.} */
1838 memset (tm, '\0', sizeof (*tm));
1839
1840 /* @r{Try the ISO format first.} */
1841 cp = strptime (input, "%F", tm);
1842 if (cp == NULL)
1843 @{
1844 /* @r{Does not match. Try the US form.} */
1845 cp = strptime (input, "%D", tm);
1846 @}
1847
1848 return cp;
1849@}
1850@end smallexample
1851
1852@node General Time String Parsing
76c23bac 1853@subsubsection A More User-friendly Way to Parse Times and Dates
e9dcb080 1854
76c23bac
UD
1855The Unix standard defines another function for parsing date strings.
1856The interface is weird, but if the function happens to suit your
1857application it is just fine. It is problematic to use this function
1858in multi-threaded programs or libraries, since it returns a pointer to
1859a static variable, and uses a global variable and global state (an
1860environment variable).
e9dcb080
UD
1861
1862@comment time.h
1863@comment Unix98
1864@defvar getdate_err
76c23bac
UD
1865This variable of type @code{int} contains the error code of the last
1866unsuccessful call to @code{getdate}. Defined values are:
e9dcb080
UD
1867
1868@table @math
1869@item 1
1870The environment variable @code{DATEMSK} is not defined or null.
1871@item 2
1872The template file denoted by the @code{DATEMSK} environment variable
1873cannot be opened.
1874@item 3
1875Information about the template file cannot retrieved.
1876@item 4
76c23bac 1877The template file is not a regular file.
e9dcb080
UD
1878@item 5
1879An I/O error occurred while reading the template file.
1880@item 6
1881Not enough memory available to execute the function.
1882@item 7
1883The template file contains no matching template.
1884@item 8
76c23bac
UD
1885The input date is invalid, but would match a template otherwise. This
1886includes dates like February 31st, and dates which cannot be represented
1887in a @code{time_t} variable.
e9dcb080
UD
1888@end table
1889@end defvar
1890
1891@comment time.h
1892@comment Unix98
1893@deftypefun {struct tm *} getdate (const char *@var{string})
76c23bac
UD
1894The interface to @code{getdate} is the simplest possible for a function
1895to parse a string and return the value. @var{string} is the input
1896string and the result is returned in a statically-allocated variable.
e9dcb080 1897
76c23bac
UD
1898The details about how the string is processed are hidden from the user.
1899In fact, they can be outside the control of the program. Which formats
e9dcb080 1900are recognized is controlled by the file named by the environment
76c23bac 1901variable @code{DATEMSK}. This file should contain
e9dcb080
UD
1902lines of valid format strings which could be passed to @code{strptime}.
1903
1904The @code{getdate} function reads these format strings one after the
1905other and tries to match the input string. The first line which
1906completely matches the input string is used.
1907
76c23bac
UD
1908Elements not initialized through the format string retain the values
1909present at the time of the @code{getdate} function call.
e9dcb080 1910
76c23bac 1911The formats recognized by @code{getdate} are the same as for
e9dcb080 1912@code{strptime}. See above for an explanation. There are only a few
76c23bac 1913extensions to the @code{strptime} behavior:
e9dcb080
UD
1914
1915@itemize @bullet
1916@item
1917If the @code{%Z} format is given the broken-down time is based on the
76c23bac 1918current time of the timezone matched, not of the current timezone of the
e9dcb080
UD
1919runtime environment.
1920
1921@emph{Note}: This is not implemented (currently). The problem is that
1922timezone names are not unique. If a fixed timezone is assumed for a
76c23bac 1923given string (say @code{EST} meaning US East Coast time), then uses for
e9dcb080 1924countries other than the USA will fail. So far we have found no good
76c23bac 1925solution to this.
e9dcb080
UD
1926
1927@item
1928If only the weekday is specified the selected day depends on the current
1929date. If the current weekday is greater or equal to the @code{tm_wday}
76c23bac 1930value the current week's day is chosen, otherwise the day next week is chosen.
e9dcb080
UD
1931
1932@item
76c23bac
UD
1933A similar heuristic is used when only the month is given and not the
1934year. If the month is greater than or equal to the current month, then
1935the current year is used. Otherwise it wraps to next year. The first
1936day of the month is assumed if one is not explicitly specified.
e9dcb080
UD
1937
1938@item
76c23bac 1939The current hour, minute, and second are used if the appropriate value is
e9dcb080
UD
1940not set through the format.
1941
1942@item
76c23bac
UD
1943If no date is given tomorrow's date is used if the time is
1944smaller than the current time. Otherwise today's date is taken.
e9dcb080
UD
1945@end itemize
1946
1947It should be noted that the format in the template file need not only
1948contain format elements. The following is a list of possible format
1949strings (taken from the Unix standard):
1950
1951@smallexample
1952%m
1953%A %B %d, %Y %H:%M:%S
1954%A
1955%B
1956%m/%d/%y %I %p
1957%d,%m,%Y %H:%M
1958at %A the %dst of %B in %Y
1959run job at %I %p,%B %dnd
1960%A den %d. %B %Y %H.%M Uhr
1961@end smallexample
1962
76c23bac 1963As you can see, the template list can contain very specific strings like
e9dcb080 1964@code{run job at %I %p,%B %dnd}. Using the above list of templates and
76c23bac 1965assuming the current time is Mon Sep 22 12:19:47 EDT 1986 we can obtain the
16a8520f 1966following results for the given input.
e9dcb080 1967
16a8520f 1968@multitable {xxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
76c23bac 1969@item Input @tab Match @tab Result
e9dcb080
UD
1970@item Mon @tab %a @tab Mon Sep 22 12:19:47 EDT 1986
1971@item Sun @tab %a @tab Sun Sep 28 12:19:47 EDT 1986
1972@item Fri @tab %a @tab Fri Sep 26 12:19:47 EDT 1986
1973@item September @tab %B @tab Mon Sep 1 12:19:47 EDT 1986
1974@item January @tab %B @tab Thu Jan 1 12:19:47 EST 1987
1975@item December @tab %B @tab Mon Dec 1 12:19:47 EST 1986
1976@item Sep Mon @tab %b %a @tab Mon Sep 1 12:19:47 EDT 1986
1977@item Jan Fri @tab %b %a @tab Fri Jan 2 12:19:47 EST 1987
1978@item Dec Mon @tab %b %a @tab Mon Dec 1 12:19:47 EST 1986
1979@item Jan Wed 1989 @tab %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
1980@item Fri 9 @tab %a %H @tab Fri Sep 26 09:00:00 EDT 1986
1981@item Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
1982@item 10:30 @tab %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
1983@item 13:30 @tab %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
1984@end multitable
1985
1986The return value of the function is a pointer to a static variable of
76c23bac
UD
1987type @w{@code{struct tm}}, or a null pointer if an error occurred. The
1988result is only valid until the next @code{getdate} call, making this
1989function unusable in multi-threaded applications.
e9dcb080
UD
1990
1991The @code{errno} variable is @emph{not} changed. Error conditions are
76c23bac 1992stored in the global variable @code{getdate_err}. See the
e9dcb080 1993description above for a list of the possible error values.
c730d678
UD
1994
1995@emph{Warning:} The @code{getdate} function should @emph{never} be
1996used in SUID-programs. The reason is obvious: using the
76c23bac 1997@code{DATEMSK} environment variable you can get the function to open
16a8520f 1998any arbitrary file and chances are high that with some bogus input
c730d678
UD
1999(such as a binary file) the program will crash.
2000@end deftypefun
2001
2002@comment time.h
2003@comment GNU
2004@deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
2005The @code{getdate_r} function is the reentrant counterpart of
2006@code{getdate}. It does not use the global variable @code{getdate_err}
76c23bac
UD
2007to signal an error, but instead returns an error code. The same error
2008codes as described in the @code{getdate_err} documentation above are
2009used, with 0 meaning success.
c730d678 2010
76c23bac
UD
2011Moreover, @code{getdate_r} stores the broken-down time in the variable
2012of type @code{struct tm} pointed to by the second argument, rather than
2013in a static variable.
c730d678
UD
2014
2015This function is not defined in the Unix standard. Nevertheless it is
2016available on some other Unix systems as well.
2017
76c23bac
UD
2018The warning against using @code{getdate} in SUID-programs applies to
2019@code{getdate_r} as well.
e9dcb080
UD
2020@end deftypefun
2021
28f540f4
RM
2022@node TZ Variable
2023@subsection Specifying the Time Zone with @code{TZ}
2024
2025In POSIX systems, a user can specify the time zone by means of the
2026@code{TZ} environment variable. For information about how to set
2027environment variables, see @ref{Environment Variables}. The functions
2028for accessing the time zone are declared in @file{time.h}.
2029@pindex time.h
2030@cindex time zone
2031
2032You should not normally need to set @code{TZ}. If the system is
f0f1bf85 2033configured properly, the default time zone will be correct. You might
76c23bac
UD
2034set @code{TZ} if you are using a computer over a network from a
2035different time zone, and would like times reported to you in the time
2036zone local to you, rather than what is local to the computer.
28f540f4 2037
76c23bac 2038In POSIX.1 systems the value of the @code{TZ} variable can be in one of
28f540f4
RM
2039three formats. With the GNU C library, the most common format is the
2040last one, which can specify a selection from a large database of time
2041zone information for many regions of the world. The first two formats
2042are used to describe the time zone information directly, which is both
2043more cumbersome and less precise. But the POSIX.1 standard only
2044specifies the details of the first two formats, so it is good to be
2045familiar with them in case you come across a POSIX.1 system that doesn't
2046support a time zone information database.
2047
2048The first format is used when there is no Daylight Saving Time (or
2049summer time) in the local time zone:
2050
2051@smallexample
2052@r{@var{std} @var{offset}}
2053@end smallexample
2054
2055The @var{std} string specifies the name of the time zone. It must be
76c23bac
UD
2056three or more characters long and must not contain a leading colon,
2057embedded digits, commas, nor plus and minus signs. There is no space
28f540f4
RM
2058character separating the time zone name from the @var{offset}, so these
2059restrictions are necessary to parse the specification correctly.
2060
76c23bac 2061The @var{offset} specifies the time value you must add to the local time
28f540f4
RM
2062to get a Coordinated Universal Time value. It has syntax like
2063[@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]]. This
2064is positive if the local time zone is west of the Prime Meridian and
2065negative if it is east. The hour must be between @code{0} and
01cdeca0 2066@code{23}, and the minute and seconds between @code{0} and @code{59}.
28f540f4
RM
2067
2068For example, here is how we would specify Eastern Standard Time, but
76c23bac 2069without any Daylight Saving Time alternative:
28f540f4
RM
2070
2071@smallexample
2072EST+5
2073@end smallexample
2074
2075The second format is used when there is Daylight Saving Time:
2076
2077@smallexample
2078@r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
2079@end smallexample
2080
2081The initial @var{std} and @var{offset} specify the standard time zone, as
2082described above. The @var{dst} string and @var{offset} specify the name
76c23bac 2083and offset for the corresponding Daylight Saving Time zone; if the
28f540f4
RM
2084@var{offset} is omitted, it defaults to one hour ahead of standard time.
2085
76c23bac
UD
2086The remainder of the specification describes when Daylight Saving Time is
2087in effect. The @var{start} field is when Daylight Saving Time goes into
28f540f4
RM
2088effect and the @var{end} field is when the change is made back to standard
2089time. The following formats are recognized for these fields:
2090
2091@table @code
2092@item J@var{n}
2093This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
2094February 29 is never counted, even in leap years.
2095
2096@item @var{n}
2097This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
2098February 29 is counted in leap years.
2099
2100@item M@var{m}.@var{w}.@var{d}
2101This specifies day @var{d} of week @var{w} of month @var{m}. The day
2102@var{d} must be between @code{0} (Sunday) and @code{6}. The week
2103@var{w} must be between @code{1} and @code{5}; week @code{1} is the
2104first week in which day @var{d} occurs, and week @code{5} specifies the
2105@emph{last} @var{d} day in the month. The month @var{m} should be
2106between @code{1} and @code{12}.
2107@end table
2108
2109The @var{time} fields specify when, in the local time currently in
2110effect, the change to the other time occurs. If omitted, the default is
2111@code{02:00:00}.
2112
76c23bac
UD
2113For example, here is how you would specify the Eastern time zone in the
2114United States, including the appropriate Daylight Saving Time and its dates
f0f1bf85 2115of applicability. The normal offset from UTC is 5 hours; since this is
28f540f4
RM
2116west of the prime meridian, the sign is positive. Summer time begins on
2117the first Sunday in April at 2:00am, and ends on the last Sunday in October
2118at 2:00am.
2119
2120@smallexample
f0f1bf85 2121EST+5EDT,M4.1.0/2,M10.5.0/2
28f540f4
RM
2122@end smallexample
2123
76c23bac 2124The schedule of Daylight Saving Time in any particular jurisdiction has
28f540f4
RM
2125changed over the years. To be strictly correct, the conversion of dates
2126and times in the past should be based on the schedule that was in effect
2127then. However, this format has no facilities to let you specify how the
2128schedule has changed from year to year. The most you can do is specify
2129one particular schedule---usually the present day schedule---and this is
2130used to convert any date, no matter when. For precise time zone
2131specifications, it is best to use the time zone information database
2132(see below).
2133
2134The third format looks like this:
2135
2136@smallexample
2137:@var{characters}
2138@end smallexample
2139
2140Each operating system interprets this format differently; in the GNU C
2141library, @var{characters} is the name of a file which describes the time
2142zone.
2143
2144@pindex /etc/localtime
2145@pindex localtime
2146If the @code{TZ} environment variable does not have a value, the
2147operation chooses a time zone by default. In the GNU C library, the
2148default time zone is like the specification @samp{TZ=:/etc/localtime}
2149(or @samp{TZ=:/usr/local/etc/localtime}, depending on how GNU C library
2150was configured; @pxref{Installation}). Other C libraries use their own
2151rule for choosing the default time zone, so there is little we can say
2152about them.
2153
2154@cindex time zone database
2155@pindex /share/lib/zoneinfo
2156@pindex zoneinfo
2157If @var{characters} begins with a slash, it is an absolute file name;
2158otherwise the library looks for the file
2159@w{@file{/share/lib/zoneinfo/@var{characters}}}. The @file{zoneinfo}
2160directory contains data files describing local time zones in many
2161different parts of the world. The names represent major cities, with
2162subdirectories for geographical areas; for example,
2163@file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
2164These data files are installed by the system administrator, who also
2165sets @file{/etc/localtime} to point to the data file for the local time
2166zone. The GNU C library comes with a large database of time zone
2167information for most regions of the world, which is maintained by a
2168community of volunteers and put in the public domain.
2169
2170@node Time Zone Functions
2171@subsection Functions and Variables for Time Zones
2172
2173@comment time.h
2174@comment POSIX.1
2c6fe0bd 2175@deftypevar {char *} tzname [2]
28f540f4 2176The array @code{tzname} contains two strings, which are the standard
76c23bac
UD
2177names of the pair of time zones (standard and Daylight
2178Saving) that the user has selected. @code{tzname[0]} is the name of
28f540f4 2179the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
76c23bac 2180is the name for the time zone when Daylight Saving Time is in use (for
28f540f4 2181example, @code{"EDT"}). These correspond to the @var{std} and @var{dst}
f0f1bf85 2182strings (respectively) from the @code{TZ} environment variable. If
76c23bac 2183Daylight Saving Time is never used, @code{tzname[1]} is the empty string.
28f540f4
RM
2184
2185The @code{tzname} array is initialized from the @code{TZ} environment
2186variable whenever @code{tzset}, @code{ctime}, @code{strftime},
f0f1bf85
UD
2187@code{mktime}, or @code{localtime} is called. If multiple abbreviations
2188have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
2189Time and Eastern Daylight Time), the array contains the most recent
2190abbreviation.
2191
2192The @code{tzname} array is required for POSIX.1 compatibility, but in
2193GNU programs it is better to use the @code{tm_zone} member of the
2194broken-down time structure, since @code{tm_zone} reports the correct
2195abbreviation even when it is not the latest one.
2196
76c23bac 2197Though the strings are declared as @code{char *} the user must refrain
f2ea0f5b 2198from modifying these strings. Modifying the strings will almost certainly
0413b54c
UD
2199lead to trouble.
2200
28f540f4
RM
2201@end deftypevar
2202
2203@comment time.h
2204@comment POSIX.1
2205@deftypefun void tzset (void)
2206The @code{tzset} function initializes the @code{tzname} variable from
2207the value of the @code{TZ} environment variable. It is not usually
2208necessary for your program to call this function, because it is called
2209automatically when you use the other time conversion functions that
2210depend on the time zone.
2211@end deftypefun
2212
2213The following variables are defined for compatibility with System V
f0f1bf85
UD
2214Unix. Like @code{tzname}, these variables are set by calling
2215@code{tzset} or the other time conversion functions.
28f540f4
RM
2216
2217@comment time.h
2218@comment SVID
2219@deftypevar {long int} timezone
f0f1bf85
UD
2220This contains the difference between UTC and the latest local standard
2221time, in seconds west of UTC. For example, in the U.S. Eastern time
2222zone, the value is @code{5*60*60}. Unlike the @code{tm_gmtoff} member
2223of the broken-down time structure, this value is not adjusted for
2224daylight saving, and its sign is reversed. In GNU programs it is better
2225to use @code{tm_gmtoff}, since it contains the correct offset even when
2226it is not the latest one.
28f540f4
RM
2227@end deftypevar
2228
2229@comment time.h
2230@comment SVID
2231@deftypevar int daylight
76c23bac
UD
2232This variable has a nonzero value if Daylight Saving Time rules apply.
2233A nonzero value does not necessarily mean that Daylight Saving Time is
2234now in effect; it means only that Daylight Saving Time is sometimes in
60092701 2235effect.
28f540f4
RM
2236@end deftypevar
2237
2238@node Time Functions Example
2239@subsection Time Functions Example
2240
3566d33c
UD
2241Here is an example program showing the use of some of the calendar time
2242functions.
28f540f4
RM
2243
2244@smallexample
2245@include strftim.c.texi
2246@end smallexample
2247
2248It produces output like this:
2249
2250@smallexample
2251Wed Jul 31 13:02:36 1991
2252Today is Wednesday, July 31.
2253The time is 01:02 PM.
2254@end smallexample
2255
2256
2257@node Setting an Alarm
2258@section Setting an Alarm
2259
2260The @code{alarm} and @code{setitimer} functions provide a mechanism for a
99a20616 2261process to interrupt itself in the future. They do this by setting a
28f540f4
RM
2262timer; when the timer expires, the process receives a signal.
2263
2264@cindex setting an alarm
2265@cindex interval timer, setting
2266@cindex alarms, setting
2267@cindex timers, setting
2268Each process has three independent interval timers available:
2269
2270@itemize @bullet
01cdeca0 2271@item
99a20616 2272A real-time timer that counts elapsed time. This timer sends a
28f540f4
RM
2273@code{SIGALRM} signal to the process when it expires.
2274@cindex real-time timer
2275@cindex timer, real-time
2276
01cdeca0 2277@item
99a20616 2278A virtual timer that counts processor time used by the process. This timer
28f540f4
RM
2279sends a @code{SIGVTALRM} signal to the process when it expires.
2280@cindex virtual timer
2281@cindex timer, virtual
2282
01cdeca0 2283@item
99a20616
UD
2284A profiling timer that counts both processor time used by the process,
2285and processor time spent in system calls on behalf of the process. This
2286timer sends a @code{SIGPROF} signal to the process when it expires.
28f540f4
RM
2287@cindex profiling timer
2288@cindex timer, profiling
2289
2290This timer is useful for profiling in interpreters. The interval timer
2291mechanism does not have the fine granularity necessary for profiling
2292native code.
2293@c @xref{profil} !!!
2294@end itemize
2295
2296You can only have one timer of each kind set at any given time. If you
2297set a timer that has not yet expired, that timer is simply reset to the
2298new value.
2299
2300You should establish a handler for the appropriate alarm signal using
76c23bac
UD
2301@code{signal} or @code{sigaction} before issuing a call to
2302@code{setitimer} or @code{alarm}. Otherwise, an unusual chain of events
2303could cause the timer to expire before your program establishes the
2304handler. In this case it would be terminated, since termination is the
2305default action for the alarm signals. @xref{Signal Handling}.
28f540f4 2306
f51dadcc
UD
2307To be able to use the alarm function to interrupt a system call which
2308might block otherwise indefinitely it is important to @emph{not} set the
2309@code{SA_RESTART} flag when registering the signal handler using
2310@code{sigaction}. When not using @code{sigaction} things get even
2311uglier: the @code{signal} function has to fixed semantics with respect
2312to restarts. The BSD semantics for this function is to set the flag.
2313Therefore, if @code{sigaction} for whatever reason cannot be used, it is
2314necessary to use @code{sysv_signal} and not @code{signal}.
2315
28f540f4
RM
2316The @code{setitimer} function is the primary means for setting an alarm.
2317This facility is declared in the header file @file{sys/time.h}. The
2318@code{alarm} function, declared in @file{unistd.h}, provides a somewhat
2319simpler interface for setting the real-time timer.
2320@pindex unistd.h
2321@pindex sys/time.h
2322
2323@comment sys/time.h
2324@comment BSD
2325@deftp {Data Type} {struct itimerval}
2326This structure is used to specify when a timer should expire. It contains
2327the following members:
2328@table @code
2329@item struct timeval it_interval
99a20616 2330This is the period between successive timer interrupts. If zero, the
28f540f4
RM
2331alarm will only be sent once.
2332
2333@item struct timeval it_value
99a20616
UD
2334This is the period between now and the first timer interrupt. If zero,
2335the alarm is disabled.
28f540f4
RM
2336@end table
2337
99a20616 2338The @code{struct timeval} data type is described in @ref{Elapsed Time}.
28f540f4
RM
2339@end deftp
2340
2341@comment sys/time.h
2342@comment BSD
2343@deftypefun int setitimer (int @var{which}, struct itimerval *@var{new}, struct itimerval *@var{old})
01cdeca0 2344The @code{setitimer} function sets the timer specified by @var{which}
28f540f4
RM
2345according to @var{new}. The @var{which} argument can have a value of
2346@code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
2347
2348If @var{old} is not a null pointer, @code{setitimer} returns information
2349about any previous unexpired timer of the same kind in the structure it
2350points to.
2351
2352The return value is @code{0} on success and @code{-1} on failure. The
2353following @code{errno} error conditions are defined for this function:
2354
2355@table @code
2356@item EINVAL
99a20616 2357The timer period is too large.
28f540f4
RM
2358@end table
2359@end deftypefun
2360
2361@comment sys/time.h
2362@comment BSD
2363@deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
2364The @code{getitimer} function stores information about the timer specified
2365by @var{which} in the structure pointed at by @var{old}.
2366
2367The return value and error conditions are the same as for @code{setitimer}.
2368@end deftypefun
2369
2370@comment sys/time.h
2371@comment BSD
b642f101 2372@vtable @code
28f540f4 2373@item ITIMER_REAL
28f540f4
RM
2374This constant can be used as the @var{which} argument to the
2375@code{setitimer} and @code{getitimer} functions to specify the real-time
2376timer.
2377
2378@comment sys/time.h
2379@comment BSD
2380@item ITIMER_VIRTUAL
28f540f4
RM
2381This constant can be used as the @var{which} argument to the
2382@code{setitimer} and @code{getitimer} functions to specify the virtual
2383timer.
2384
2385@comment sys/time.h
2386@comment BSD
2387@item ITIMER_PROF
28f540f4
RM
2388This constant can be used as the @var{which} argument to the
2389@code{setitimer} and @code{getitimer} functions to specify the profiling
2390timer.
b642f101 2391@end vtable
28f540f4
RM
2392
2393@comment unistd.h
2394@comment POSIX.1
2395@deftypefun {unsigned int} alarm (unsigned int @var{seconds})
2396The @code{alarm} function sets the real-time timer to expire in
2397@var{seconds} seconds. If you want to cancel any existing alarm, you
2398can do this by calling @code{alarm} with a @var{seconds} argument of
2399zero.
2400
2401The return value indicates how many seconds remain before the previous
2402alarm would have been sent. If there is no previous alarm, @code{alarm}
2403returns zero.
2404@end deftypefun
2405
2406The @code{alarm} function could be defined in terms of @code{setitimer}
2407like this:
2408
2409@smallexample
2410unsigned int
2411alarm (unsigned int seconds)
2412@{
2413 struct itimerval old, new;
2414 new.it_interval.tv_usec = 0;
2415 new.it_interval.tv_sec = 0;
2416 new.it_value.tv_usec = 0;
2417 new.it_value.tv_sec = (long int) seconds;
2418 if (setitimer (ITIMER_REAL, &new, &old) < 0)
2419 return 0;
2420 else
2421 return old.it_value.tv_sec;
2422@}
2423@end smallexample
2424
2425There is an example showing the use of the @code{alarm} function in
2426@ref{Handler Returns}.
2427
2428If you simply want your process to wait for a given number of seconds,
2429you should use the @code{sleep} function. @xref{Sleeping}.
2430
2431You shouldn't count on the signal arriving precisely when the timer
2432expires. In a multiprocessing environment there is typically some
2433amount of delay involved.
2434
2435@strong{Portability Note:} The @code{setitimer} and @code{getitimer}
2436functions are derived from BSD Unix, while the @code{alarm} function is
2437specified by the POSIX.1 standard. @code{setitimer} is more powerful than
2438@code{alarm}, but @code{alarm} is more widely used.
2439
2440@node Sleeping
2441@section Sleeping
2442
2443The function @code{sleep} gives a simple way to make the program wait
99a20616
UD
2444for a short interval. If your program doesn't use signals (except to
2445terminate), then you can expect @code{sleep} to wait reliably throughout
2446the specified interval. Otherwise, @code{sleep} can return sooner if a
2447signal arrives; if you want to wait for a given interval regardless of
2448signals, use @code{select} (@pxref{Waiting for I/O}) and don't specify
2449any descriptors to wait for.
28f540f4
RM
2450@c !!! select can get EINTR; using SA_RESTART makes sleep win too.
2451
2452@comment unistd.h
2453@comment POSIX.1
2454@deftypefun {unsigned int} sleep (unsigned int @var{seconds})
2455The @code{sleep} function waits for @var{seconds} or until a signal
01cdeca0 2456is delivered, whichever happens first.
28f540f4 2457
99a20616
UD
2458If @code{sleep} function returns because the requested interval is over,
2459it returns a value of zero. If it returns because of delivery of a
2460signal, its return value is the remaining time in the sleep interval.
28f540f4
RM
2461
2462The @code{sleep} function is declared in @file{unistd.h}.
2463@end deftypefun
2464
2465Resist the temptation to implement a sleep for a fixed amount of time by
2466using the return value of @code{sleep}, when nonzero, to call
2467@code{sleep} again. This will work with a certain amount of accuracy as
2468long as signals arrive infrequently. But each signal can cause the
2469eventual wakeup time to be off by an additional second or so. Suppose a
2470few signals happen to arrive in rapid succession by bad luck---there is
2471no limit on how much this could shorten or lengthen the wait.
2472
99a20616
UD
2473Instead, compute the calendar time at which the program should stop
2474waiting, and keep trying to wait until that calendar time. This won't
2475be off by more than a second. With just a little more work, you can use
2476@code{select} and make the waiting period quite accurate. (Of course,
2477heavy system load can cause additional unavoidable delays---unless the
2478machine is dedicated to one application, there is no way you can avoid
2479this.)
28f540f4
RM
2480
2481On some systems, @code{sleep} can do strange things if your program uses
2482@code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being
2483ignored or blocked when @code{sleep} is called, @code{sleep} might
2484return prematurely on delivery of a @code{SIGALRM} signal. If you have
2485established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
2486signal is delivered while the process is sleeping, the action taken
2487might be just to cause @code{sleep} to return instead of invoking your
2488handler. And, if @code{sleep} is interrupted by delivery of a signal
2489whose handler requests an alarm or alters the handling of @code{SIGALRM},
2490this handler and @code{sleep} will interfere.
2491
2492On the GNU system, it is safe to use @code{sleep} and @code{SIGALRM} in
2493the same program, because @code{sleep} does not work by means of
2494@code{SIGALRM}.
2495
dfd2257a
UD
2496@comment time.h
2497@comment POSIX.1
2498@deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
99a20616
UD
2499If resolution to seconds is not enough the @code{nanosleep} function can
2500be used. As the name suggests the sleep interval can be specified in
2501nanoseconds. The actual elapsed time of the sleep interval might be
2502longer since the system rounds the elapsed time you request up to the
2503next integer multiple of the actual resolution the system can deliver.
dfd2257a 2504
99a20616
UD
2505*@code{requested_time} is the elapsed time of the interval you want to
2506sleep.
2507
2508The function returns as *@code{remaining} the elapsed time left in the
2509interval for which you requested to sleep. If the interval completed
2510without getting interrupted by a signal, this is zero.
2511
b642f101 2512@code{struct timespec} is described in @xref{Elapsed Time}.
99a20616
UD
2513
2514If the function returns because the interval is over the return value is
591e1ffb 2515zero. If the function returns @math{-1} the global variable @var{errno}
dfd2257a
UD
2516is set to the following values:
2517
2518@table @code
2519@item EINTR
2520The call was interrupted because a signal was delivered to the thread.
2521If the @var{remaining} parameter is not the null pointer the structure
99a20616
UD
2522pointed to by @var{remaining} is updated to contain the remaining
2523elapsed time.
dfd2257a
UD
2524
2525@item EINVAL
2526The nanosecond value in the @var{requested_time} parameter contains an
2527illegal value. Either the value is negative or greater than or equal to
25281000 million.
2529@end table
2530
76c23bac 2531This function is a cancellation point in multi-threaded programs. This
dfd2257a
UD
2532is a problem if the thread allocates some resources (like memory, file
2533descriptors, semaphores or whatever) at the time @code{nanosleep} is
2534called. If the thread gets canceled these resources stay allocated
2535until the program ends. To avoid this calls to @code{nanosleep} should
76c23bac 2536be protected using cancellation handlers.
dfd2257a
UD
2537@c ref pthread_cleanup_push / pthread_cleanup_pop
2538
2539The @code{nanosleep} function is declared in @file{time.h}.
2540@end deftypefun