Update.
[glibc.git] / manual / time.texi
blob7084e7f1103326266b5e9ca9ed58a04d52a687d5
1 @node Date and Time, Non-Local Exits, Arithmetic, Top
2 @c %MENU% Functions for getting the date and time and formatting them nicely
3 @chapter Date and Time
5 This chapter describes functions for manipulating dates and times,
6 including functions for determining what the current time is and
7 conversion between different time representations.
9 The time functions fall into three main categories:
11 @itemize @bullet
12 @item
13 Functions for measuring elapsed CPU time are discussed in @ref{Processor
14 Time}.
16 @item
17 Functions for measuring absolute clock or calendar time are discussed in
18 @ref{Calendar Time}.
20 @item
21 Functions for setting alarms and timers are discussed in @ref{Setting
22 an Alarm}.
23 @end itemize
25 @menu
26 * Processor Time::              Measures processor time used by a program.
27 * Calendar Time::               Manipulation of ``real'' dates and times.
28 * Precision Time::              Manipulation and monitoring of high accuracy
29                                   time.
30 * Setting an Alarm::            Sending a signal after a specified time.
31 * Sleeping::                    Waiting for a period of time.
32 * Resource Usage::              Measuring various resources used.
33 * Limits on Resources::         Specifying limits on resource usage.
34 * Priority::                    Reading or setting process run priority.
35 @end menu
37 @node Processor Time
38 @section Processor Time
40 If you're trying to optimize your program or measure its efficiency, it's
41 very useful to be able to know how much @dfn{processor time} or @dfn{CPU
42 time} it has used at any given point.  Processor time is different from
43 actual wall clock time because it doesn't include any time spent waiting
44 for I/O or when some other process is running.  Processor time is
45 represented by the data type @code{clock_t}, and is given as a number of
46 @dfn{clock ticks} relative to an arbitrary base time marking the beginning
47 of a single program invocation.
48 @cindex CPU time
49 @cindex processor time
50 @cindex clock ticks
51 @cindex ticks, clock
52 @cindex time, elapsed CPU
54 @menu
55 * Basic CPU Time::              The @code{clock} function.
56 * Detailed CPU Time::           The @code{times} function.
57 @end menu
59 @node Basic CPU Time
60 @subsection Basic CPU Time Inquiry
62 To get the elapsed CPU time used by a process, you can use the
63 @code{clock} function.  This facility is declared in the header file
64 @file{time.h}.
65 @pindex time.h
67 In typical usage, you call the @code{clock} function at the beginning and
68 end of the interval you want to time, subtract the values, and then divide
69 by @code{CLOCKS_PER_SEC} (the number of clock ticks per second), like this:
71 @smallexample
72 @group
73 #include <time.h>
75 clock_t start, end;
76 double elapsed;
78 start = clock();
79 @dots{} /* @r{Do the work.} */
80 end = clock();
81 elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
82 @end group
83 @end smallexample
85 Different computers and operating systems vary wildly in how they keep
86 track of processor time.  It's common for the internal processor clock
87 to have a resolution somewhere between hundredth and millionth of a
88 second.
90 In the GNU system, @code{clock_t} is equivalent to @code{long int} and
91 @code{CLOCKS_PER_SEC} is an integer value.  But in other systems, both
92 @code{clock_t} and the type of the macro @code{CLOCKS_PER_SEC} can be
93 either integer or floating-point types.  Casting processor time values
94 to @code{double}, as in the example above, makes sure that operations
95 such as arithmetic and printing work properly and consistently no matter
96 what the underlying representation is.
98 @comment time.h
99 @comment ISO
100 @deftypevr Macro int CLOCKS_PER_SEC
101 The value of this macro is the number of clock ticks per second measured
102 by the @code{clock} function.
103 @end deftypevr
105 @comment time.h
106 @comment POSIX.1
107 @deftypevr Macro int CLK_TCK
108 This is an obsolete name for @code{CLOCKS_PER_SEC}.
109 @end deftypevr
111 @comment time.h
112 @comment ISO
113 @deftp {Data Type} clock_t
114 This is the type of the value returned by the @code{clock} function.
115 Values of type @code{clock_t} are in units of clock ticks.
116 @end deftp
118 @comment time.h
119 @comment ISO
120 @deftypefun clock_t clock (void)
121 This function returns the elapsed processor time.  The base time is
122 arbitrary but doesn't change within a single process.  If the processor
123 time is not available or cannot be represented, @code{clock} returns the
124 value @code{(clock_t)(-1)}.
125 @end deftypefun
128 @node Detailed CPU Time
129 @subsection Detailed Elapsed CPU Time Inquiry
131 The @code{times} function returns more detailed information about
132 elapsed processor time in a @w{@code{struct tms}} object.  You should
133 include the header file @file{sys/times.h} to use this facility.
134 @pindex sys/times.h
136 @comment sys/times.h
137 @comment POSIX.1
138 @deftp {Data Type} {struct tms}
139 The @code{tms} structure is used to return information about process
140 times.  It contains at least the following members:
142 @table @code
143 @item clock_t tms_utime
144 This is the CPU time used in executing the instructions of the calling
145 process.
147 @item clock_t tms_stime
148 This is the CPU time used by the system on behalf of the calling process.
150 @item clock_t tms_cutime
151 This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
152 values of all terminated child processes of the calling process, whose
153 status has been reported to the parent process by @code{wait} or
154 @code{waitpid}; see @ref{Process Completion}.  In other words, it
155 represents the total CPU time used in executing the instructions of all
156 the terminated child processes of the calling process, excluding child
157 processes which have not yet been reported by @code{wait} or
158 @code{waitpid}.
160 @item clock_t tms_cstime
161 This is similar to @code{tms_cutime}, but represents the total CPU time
162 used by the system on behalf of all the terminated child processes of the
163 calling process.
164 @end table
166 All of the times are given in clock ticks.  These are absolute values; in a
167 newly created process, they are all zero.  @xref{Creating a Process}.
168 @end deftp
170 @comment sys/times.h
171 @comment POSIX.1
172 @deftypefun clock_t times (struct tms *@var{buffer})
173 The @code{times} function stores the processor time information for
174 the calling process in @var{buffer}.
176 The return value is the same as the value of @code{clock()}: the elapsed
177 real time relative to an arbitrary base.  The base is a constant within a
178 particular process, and typically represents the time since system
179 start-up.  A value of @code{(clock_t)(-1)} is returned to indicate failure.
180 @end deftypefun
182 @strong{Portability Note:} The @code{clock} function described in
183 @ref{Basic CPU Time}, is specified by the @w{ISO C} standard.  The
184 @code{times} function is a feature of POSIX.1.  In the GNU system, the
185 value returned by the @code{clock} function is equivalent to the sum of
186 the @code{tms_utime} and @code{tms_stime} fields returned by
187 @code{times}.
189 @node Calendar Time
190 @section Calendar Time
192 This section describes facilities for keeping track of dates and times
193 according to the Gregorian calendar.
194 @cindex Gregorian calendar
195 @cindex time, calendar
196 @cindex date and time
198 There are three representations for date and time information:
200 @itemize @bullet
201 @item
202 @dfn{Calendar time} (the @code{time_t} data type) is a compact
203 representation, typically giving the number of seconds elapsed since
204 some implementation-specific base time.
205 @cindex calendar time
207 @item
208 There is also a @dfn{high-resolution time} representation (the @code{struct
209 timeval} data type) that includes fractions of a second.  Use this time
210 representation instead of ordinary calendar time when you need greater
211 precision.
212 @cindex high-resolution time
214 @item
215 @dfn{Local time} or @dfn{broken-down time} (the @code{struct
216 tm} data type) represents the date and time as a set of components
217 specifying the year, month, and so on, for a specific time zone.
218 This time representation is usually used in conjunction with formatting
219 date and time values.
220 @cindex local time
221 @cindex broken-down time
222 @end itemize
224 @menu
225 * Simple Calendar Time::        Facilities for manipulating calendar time.
226 * High-Resolution Calendar::    A time representation with greater precision.
227 * Broken-down Time::            Facilities for manipulating local time.
228 * Formatting Date and Time::    Converting times to strings.
229 * Parsing Date and Time::       Convert textual time and date information back
230                                  into broken-down time values.
231 * TZ Variable::                 How users specify the time zone.
232 * Time Zone Functions::         Functions to examine or specify the time zone.
233 * Time Functions Example::      An example program showing use of some of
234                                  the time functions.
235 @end menu
237 @node Simple Calendar Time
238 @subsection Simple Calendar Time
240 This section describes the @code{time_t} data type for representing
241 calendar time, and the functions which operate on calendar time objects.
242 These facilities are declared in the header file @file{time.h}.
243 @pindex time.h
245 @cindex epoch
246 @comment time.h
247 @comment ISO
248 @deftp {Data Type} time_t
249 This is the data type used to represent calendar time.
250 When interpreted as an absolute time
251 value, it represents the number of seconds elapsed since 00:00:00 on
252 January 1, 1970, Coordinated Universal Time.  (This date is sometimes
253 referred to as the @dfn{epoch}.)  POSIX requires that this count
254 ignore leap seconds, but on some hosts this count includes leap seconds
255 if you set @code{TZ} to certain values (@pxref{TZ Variable}).
257 In the GNU C library, @code{time_t} is equivalent to @code{long int}.
258 In other systems, @code{time_t} might be either an integer or
259 floating-point type.
260 @end deftp
262 @comment time.h
263 @comment ISO
264 @deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
265 The @code{difftime} function returns the number of seconds elapsed
266 between time @var{time1} and time @var{time0}, as a value of type
267 @code{double}.  The difference ignores leap seconds unless leap
268 second support is enabled.
270 In the GNU system, you can simply subtract @code{time_t} values.  But on
271 other systems, the @code{time_t} data type might use some other encoding
272 where subtraction doesn't work directly.
273 @end deftypefun
275 @comment time.h
276 @comment ISO
277 @deftypefun time_t time (time_t *@var{result})
278 The @code{time} function returns the current time as a value of type
279 @code{time_t}.  If the argument @var{result} is not a null pointer, the
280 time value is also stored in @code{*@var{result}}.  If the calendar
281 time is not available, the value @w{@code{(time_t)(-1)}} is returned.
282 @end deftypefun
285 @node High-Resolution Calendar
286 @subsection High-Resolution Calendar
288 The @code{time_t} data type used to represent calendar times has a
289 resolution of only one second.  Some applications need more precision.
291 So, the GNU C library also contains functions which are capable of
292 representing calendar times to a higher resolution than one second.  The
293 functions and the associated data types described in this section are
294 declared in @file{sys/time.h}.
295 @pindex sys/time.h
297 @comment sys/time.h
298 @comment BSD
299 @deftp {Data Type} {struct timeval}
300 The @code{struct timeval} structure represents a calendar time.  It
301 has the following members:
303 @table @code
304 @item long int tv_sec
305 This represents the number of seconds since the epoch.  It is equivalent
306 to a normal @code{time_t} value.
308 @item long int tv_usec
309 This is the fractional second value, represented as the number of
310 microseconds.
312 Some times struct timeval values are used for time intervals.  Then the
313 @code{tv_sec} member is the number of seconds in the interval, and
314 @code{tv_usec} is the number of additional microseconds.
315 @end table
316 @end deftp
318 @comment sys/time.h
319 @comment BSD
320 @deftp {Data Type} {struct timezone}
321 The @code{struct timezone} structure is used to hold minimal information
322 about the local time zone.  It has the following members:
324 @table @code
325 @item int tz_minuteswest
326 This is the number of minutes west of UTC.
328 @item int tz_dsttime
329 If nonzero, daylight saving time applies during some part of the year.
330 @end table
332 The @code{struct timezone} type is obsolete and should never be used.
333 Instead, use the facilities described in @ref{Time Zone Functions}.
334 @end deftp
336 It is often necessary to subtract two values of type @w{@code{struct
337 timeval}}.  Here is the best way to do this.  It works even on some
338 peculiar operating systems where the @code{tv_sec} member has an
339 unsigned type.
341 @smallexample
342 /* @r{Subtract the `struct timeval' values X and Y,}
343    @r{storing the result in RESULT.}
344    @r{Return 1 if the difference is negative, otherwise 0.}  */
347 timeval_subtract (result, x, y)
348      struct timeval *result, *x, *y;
350   /* @r{Perform the carry for the later subtraction by updating @var{y}.} */
351   if (x->tv_usec < y->tv_usec) @{
352     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
353     y->tv_usec -= 1000000 * nsec;
354     y->tv_sec += nsec;
355   @}
356   if (x->tv_usec - y->tv_usec > 1000000) @{
357     int nsec = (y->tv_usec - x->tv_usec) / 1000000;
358     y->tv_usec += 1000000 * nsec;
359     y->tv_sec -= nsec;
360   @}
362   /* @r{Compute the time remaining to wait.}
363      @r{@code{tv_usec} is certainly positive.} */
364   result->tv_sec = x->tv_sec - y->tv_sec;
365   result->tv_usec = x->tv_usec - y->tv_usec;
367   /* @r{Return 1 if result is negative.} */
368   return x->tv_sec < y->tv_sec;
370 @end smallexample
372 @comment sys/time.h
373 @comment BSD
374 @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
375 The @code{gettimeofday} function returns the current date and time in the
376 @code{struct timeval} structure indicated by @var{tp}.  Information about the
377 time zone is returned in the structure pointed at @var{tzp}.  If the @var{tzp}
378 argument is a null pointer, time zone information is ignored.
380 The return value is @code{0} on success and @code{-1} on failure.  The
381 following @code{errno} error condition is defined for this function:
383 @table @code
384 @item ENOSYS
385 The operating system does not support getting time zone information, and
386 @var{tzp} is not a null pointer.  The GNU operating system does not
387 support using @w{@code{struct timezone}} to represent time zone
388 information; that is an obsolete feature of 4.3 BSD.
389 Instead, use the facilities described in @ref{Time Zone Functions}.
390 @end table
391 @end deftypefun
393 @comment sys/time.h
394 @comment BSD
395 @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
396 The @code{settimeofday} function sets the current date and time
397 according to the arguments.  As for @code{gettimeofday}, time zone
398 information is ignored if @var{tzp} is a null pointer.
400 You must be a privileged user in order to use @code{settimeofday}.
402 The return value is @code{0} on success and @code{-1} on failure.  The
403 following @code{errno} error conditions are defined for this function:
405 @table @code
406 @item EPERM
407 This process cannot set the time because it is not privileged.
409 @item ENOSYS
410 The operating system does not support setting time zone information, and
411 @var{tzp} is not a null pointer.
412 @end table
413 @end deftypefun
415 @comment sys/time.h
416 @comment BSD
417 @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
418 This function speeds up or slows down the system clock in order to make
419 gradual adjustments in the current time.  This ensures that the time
420 reported by the system clock is always monotonically increasing, which
421 might not happen if you simply set the current time.
423 The @var{delta} argument specifies a relative adjustment to be made to
424 the current time.  If negative, the system clock is slowed down for a
425 while until it has lost this much time.  If positive, the system clock
426 is speeded up for a while.
428 If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
429 function returns information about any previous time adjustment that
430 has not yet completed.
432 This function is typically used to synchronize the clocks of computers
433 in a local network.  You must be a privileged user to use it.
434 The return value is @code{0} on success and @code{-1} on failure.  The
435 following @code{errno} error condition is defined for this function:
437 @table @code
438 @item EPERM
439 You do not have privilege to set the time.
440 @end table
441 @end deftypefun
443 @strong{Portability Note:}  The @code{gettimeofday}, @code{settimeofday},
444 and @code{adjtime} functions are derived from BSD.
447 @node Broken-down Time
448 @subsection Broken-down Time
449 @cindex broken-down time
450 @cindex calendar time and broken-down time
452 Calendar time is represented as a number of seconds.  This is convenient
453 for calculation, but has no resemblance to the way people normally
454 represent dates and times.  By contrast, @dfn{broken-down time} is a binary
455 representation separated into year, month, day, and so on.  Broken down
456 time values are not useful for calculations, but they are useful for
457 printing human readable time.
459 A broken-down time value is always relative to a choice of local time
460 zone, and it also indicates which time zone was used.
462 The symbols in this section are declared in the header file @file{time.h}.
464 @comment time.h
465 @comment ISO
466 @deftp {Data Type} {struct tm}
467 This is the data type used to represent a broken-down time.  The structure
468 contains at least the following members, which can appear in any order:
470 @table @code
471 @item int tm_sec
472 This is the number of seconds after the minute, normally in the range
473 @code{0} through @code{59}.  (The actual upper limit is @code{60}, to allow
474 for leap seconds if leap second support is available.)
475 @cindex leap second
477 @item int tm_min
478 This is the number of minutes after the hour, in the range @code{0} through
479 @code{59}.
481 @item int tm_hour
482 This is the number of hours past midnight, in the range @code{0} through
483 @code{23}.
485 @item int tm_mday
486 This is the day of the month, in the range @code{1} through @code{31}.
488 @item int tm_mon
489 This is the number of months since January, in the range @code{0} through
490 @code{11}.
492 @item int tm_year
493 This is the number of years since @code{1900}.
495 @item int tm_wday
496 This is the number of days since Sunday, in the range @code{0} through
497 @code{6}.
499 @item int tm_yday
500 This is the number of days since January 1, in the range @code{0} through
501 @code{365}.
503 @item int tm_isdst
504 @cindex Daylight Saving Time
505 @cindex summer time
506 This is a flag that indicates whether Daylight Saving Time is (or was, or
507 will be) in effect at the time described.  The value is positive if
508 Daylight Saving Time is in effect, zero if it is not, and negative if the
509 information is not available.
511 @item long int tm_gmtoff
512 This field describes the time zone that was used to compute this
513 broken-down time value, including any adjustment for daylight saving; it
514 is the number of seconds that you must add to UTC to get local time.
515 You can also think of this as the number of seconds east of UTC.  For
516 example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
517 The @code{tm_gmtoff} field is derived from BSD and is a GNU library
518 extension; it is not visible in a strict @w{ISO C} environment.
520 @item const char *tm_zone
521 This field is the name for the time zone that was used to compute this
522 broken-down time value.  Like @code{tm_gmtoff}, this field is a BSD and
523 GNU extension, and is not visible in a strict @w{ISO C} environment.
524 @end table
525 @end deftp
527 @comment time.h
528 @comment ISO
529 @deftypefun {struct tm *} localtime (const time_t *@var{time})
530 The @code{localtime} function converts the calendar time pointed to by
531 @var{time} to broken-down time representation, expressed relative to the
532 user's specified time zone.
534 The return value is a pointer to a static broken-down time structure, which
535 might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
536 or @code{localtime}.  (But no other library function overwrites the contents
537 of this object.)
539 The return value is the null pointer if @var{time} cannot be represented
540 as a broken-down time; typically this is because the year cannot fit into
541 an @code{int}.
543 Calling @code{localtime} has one other effect: it sets the variable
544 @code{tzname} with information about the current time zone.  @xref{Time
545 Zone Functions}.
546 @end deftypefun
548 Using the @code{localtime} function is a big problem in multi-threaded
549 programs.  The result is returned in a static buffer and this is used in
550 all threads.  POSIX.1c introduced a varient of this function.
552 @comment time.h
553 @comment POSIX.1c
554 @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
555 The @code{localtime_r} function works just like the @code{localtime}
556 function.  It takes a pointer to a variable containing the calendar time
557 and converts it to the broken-down time format.
559 But the result is not placed in a static buffer.  Instead it is placed
560 in the object of type @code{struct tm} to which the parameter
561 @var{resultp} points.
563 If the conversion is successful the function returns a pointer to the
564 object the result was written into, i.e., it returns @var{resultp}.
565 @end deftypefun
568 @comment time.h
569 @comment ISO
570 @deftypefun {struct tm *} gmtime (const time_t *@var{time})
571 This function is similar to @code{localtime}, except that the broken-down
572 time is expressed as Coordinated Universal Time (UTC)---that is, as
573 Greenwich Mean Time (GMT)---rather than relative to the local time zone.
575 Recall that calendar times are @emph{always} expressed in coordinated
576 universal time.
577 @end deftypefun
579 As for the @code{localtime} function we have the problem that the result
580 is placed in a static variable.  POSIX.1c also provides a replacement for
581 @code{gmtime}.
583 @comment time.h
584 @comment POSIX.1c
585 @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
586 This function is similar to @code{localtime_r}, except that it converts
587 just like @code{gmtime} the given time as Coordinated Universal Time.
589 If the conversion is successful the function returns a pointer to the
590 object the result was written into, i.e., it returns @var{resultp}.
591 @end deftypefun
594 @comment time.h
595 @comment ISO
596 @deftypefun time_t mktime (struct tm *@var{brokentime})
597 The @code{mktime} function is used to convert a broken-down time structure
598 to a calendar time representation.  It also ``normalizes'' the contents of
599 the broken-down time structure, by filling in the day of week and day of
600 year based on the other date and time components.
602 The @code{mktime} function ignores the specified contents of the
603 @code{tm_wday} and @code{tm_yday} members of the broken-down time
604 structure.  It uses the values of the other components to compute the
605 calendar time; it's permissible for these components to have
606 unnormalized values outside of their normal ranges.  The last thing that
607 @code{mktime} does is adjust the components of the @var{brokentime}
608 structure (including the @code{tm_wday} and @code{tm_yday}).
610 If the specified broken-down time cannot be represented as a calendar time,
611 @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
612 the contents of @var{brokentime}.
614 Calling @code{mktime} also sets the variable @code{tzname} with
615 information about the current time zone.  @xref{Time Zone Functions}.
616 @end deftypefun
618 @node Formatting Date and Time
619 @subsection Formatting Date and Time
621 The functions described in this section format time values as strings.
622 These functions are declared in the header file @file{time.h}.
623 @pindex time.h
625 @comment time.h
626 @comment ISO
627 @deftypefun {char *} asctime (const struct tm *@var{brokentime})
628 The @code{asctime} function converts the broken-down time value that
629 @var{brokentime} points to into a string in a standard format:
631 @smallexample
632 "Tue May 21 13:46:22 1991\n"
633 @end smallexample
635 The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
636 @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
638 The abbreviations for the months are: @samp{Jan}, @samp{Feb},
639 @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
640 @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
642 The return value points to a statically allocated string, which might be
643 overwritten by subsequent calls to @code{asctime} or @code{ctime}.
644 (But no other library function overwrites the contents of this
645 string.)
646 @end deftypefun
648 @comment time.h
649 @comment POSIX.1c
650 @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
651 This function is similar to @code{asctime} but instead of placing the
652 result in a static buffer it writes the string in the buffer pointed to
653 by the parameter @var{buffer}.  This buffer should have at least room
654 for 16 bytes.
656 If no error occurred the function returns a pointer to the string the
657 result was written into, i.e., it returns @var{buffer}.  Otherwise
658 return @code{NULL}.
659 @end deftypefun
662 @comment time.h
663 @comment ISO
664 @deftypefun {char *} ctime (const time_t *@var{time})
665 The @code{ctime} function is similar to @code{asctime}, except that the
666 time value is specified as a @code{time_t} calendar time value rather
667 than in broken-down local time format.  It is equivalent to
669 @smallexample
670 asctime (localtime (@var{time}))
671 @end smallexample
673 @code{ctime} sets the variable @code{tzname}, because @code{localtime}
674 does so.  @xref{Time Zone Functions}.
675 @end deftypefun
677 @comment time.h
678 @comment POSIX.1c
679 @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
680 This function is similar to @code{ctime}, only that it places the result
681 in the string pointed to by @var{buffer}.  It is equivalent to (written
682 using gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
684 @smallexample
685 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
686 @end smallexample
688 If no error occurred the function returns a pointer to the string the
689 result was written into, i.e., it returns @var{buffer}.  Otherwise
690 return @code{NULL}.
691 @end deftypefun
694 @comment time.h
695 @comment ISO
696 @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
697 This function is similar to the @code{sprintf} function (@pxref{Formatted
698 Input}), but the conversion specifications that can appear in the format
699 template @var{template} are specialized for printing components of the date
700 and time @var{brokentime} according to the locale currently specified for
701 time conversion (@pxref{Locales}).
703 Ordinary characters appearing in the @var{template} are copied to the
704 output string @var{s}; this can include multibyte character sequences.
705 Conversion specifiers are introduced by a @samp{%} character, followed
706 by an optional flag which can be one of the following.  These flags
707 are all GNU extensions. The first three affect only the output of
708 numbers:
710 @table @code
711 @item _
712 The number is padded with spaces.
714 @item -
715 The number is not padded at all.
717 @item 0
718 The number is padded with zeros even if the format specifies padding
719 with spaces.
721 @item ^
722 The output uses uppercase characters, but only if this is possible
723 (@pxref{Case Conversion}).
724 @end table
726 The default action is to pad the number with zeros to keep it a constant
727 width.  Numbers that do not have a range indicated below are never
728 padded, since there is no natural width for them.
730 Following the flag an optional specification of the width is possible.
731 This is specified in decimal notation.  If the natural size of the
732 output is of the field has less than the specified number of characters,
733 the result is written right adjusted and space padded to the given
734 size.
736 An optional modifier can follow the optional flag and width
737 specification.  The modifiers, which are POSIX.2 extensions, are:
739 @table @code
740 @item E
741 Use the locale's alternate representation for date and time.  This
742 modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
743 @code{%y} and @code{%Y} format specifiers.  In a Japanese locale, for
744 example, @code{%Ex} might yield a date format based on the Japanese
745 Emperors' reigns.
747 @item O
748 Use the locale's alternate numeric symbols for numbers.  This modifier
749 applies only to numeric format specifiers.
750 @end table
752 If the format supports the modifier but no alternate representation
753 is available, it is ignored.
755 The conversion specifier ends with a format specifier taken from the
756 following list.  The whole @samp{%} sequence is replaced in the output
757 string as follows:
759 @table @code
760 @item %a
761 The abbreviated weekday name according to the current locale.
763 @item %A
764 The full weekday name according to the current locale.
766 @item %b
767 The abbreviated month name according to the current locale.
769 @item %B
770 The full month name according to the current locale.
772 @item %c
773 The preferred date and time representation for the current locale.
775 @item %C
776 The century of the year.  This is equivalent to the greatest integer not
777 greater than the year divided by 100.
779 This format is a POSIX.2 extension.
781 @item %d
782 The day of the month as a decimal number (range @code{01} through @code{31}).
784 @item %D
785 The date using the format @code{%m/%d/%y}.
787 This format is a POSIX.2 extension.
789 @item %e
790 The day of the month like with @code{%d}, but padded with blank (range
791 @code{ 1} through @code{31}).
793 This format is a POSIX.2 extension.
795 @item %F
796 The date using the format @code{%Y-%m-%d}.  This is the form specified
797 in the @w{ISO 8601} standard and is the preferred form for all uses.
799 This format is a @w{ISO C 9X} extension.
801 @item %g
802 The year corresponding to the ISO week number, but without the century
803 (range @code{00} through @code{99}).  This has the same format and value
804 as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
805 to the previous or next year, that year is used instead.
807 This format is a GNU extension.
809 @item %G
810 The year corresponding to the ISO week number.  This has the same format
811 and value as @code{%Y}, except that if the ISO week number (see
812 @code{%V}) belongs to the previous or next year, that year is used
813 instead.
815 This format is a GNU extension.
817 @item %h
818 The abbreviated month name according to the current locale.  The action
819 is the same as for @code{%b}.
821 This format is a POSIX.2 extension.
823 @item %H
824 The hour as a decimal number, using a 24-hour clock (range @code{00} through
825 @code{23}).
827 @item %I
828 The hour as a decimal number, using a 12-hour clock (range @code{01} through
829 @code{12}).
831 @item %j
832 The day of the year as a decimal number (range @code{001} through @code{366}).
834 @item %k
835 The hour as a decimal number, using a 24-hour clock like @code{%H}, but
836 padded with blank (range @code{ 0} through @code{23}).
838 This format is a GNU extension.
840 @item %l
841 The hour as a decimal number, using a 12-hour clock like @code{%I}, but
842 padded with blank (range @code{ 1} through @code{12}).
844 This format is a GNU extension.
846 @item %m
847 The month as a decimal number (range @code{01} through @code{12}).
849 @item %M
850 The minute as a decimal number (range @code{00} through @code{59}).
852 @item %n
853 A single @samp{\n} (newline) character.
855 This format is a POSIX.2 extension.
857 @item %p
858 Either @samp{AM} or @samp{PM}, according to the given time value; or the
859 corresponding strings for the current locale.  Noon is treated as
860 @samp{PM} and midnight as @samp{AM}.
862 @ignore
863 We currently have a problem with makeinfo.  Write @samp{AM} and @samp{am}
864 both results in `am'.  I.e., the difference in case is not visible anymore.
865 @end ignore
866 @item %P
867 Either @samp{am} or @samp{pm}, according to the given time value; or the
868 corresponding strings for the current locale, printed in lowercase
869 characters.  Noon is treated as @samp{pm} and midnight as @samp{am}.
871 This format is a GNU extension.
873 @item %r
874 The complete time using the AM/PM format of the current locale.
876 This format is a POSIX.2 extension.
878 @item %R
879 The hour and minute in decimal numbers using the format @code{%H:%M}.
881 This format is a GNU extension.
883 @item %s
884 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
885 Leap seconds are not counted unless leap second support is available.
887 This format is a GNU extension.
889 @item %S
890 The seconds as a decimal number (range @code{00} through @code{60}).
892 @item %t
893 A single @samp{\t} (tabulator) character.
895 This format is a POSIX.2 extension.
897 @item %T
898 The time using decimal numbers using the format @code{%H:%M:%S}.
900 This format is a POSIX.2 extension.
902 @item %u
903 The day of the week as a decimal number (range @code{1} through
904 @code{7}), Monday being @code{1}.
906 This format is a POSIX.2 extension.
908 @item %U
909 The week number of the current year as a decimal number (range @code{00}
910 through @code{53}), starting with the first Sunday as the first day of
911 the first week.  Days preceding the first Sunday in the year are
912 considered to be in week @code{00}.
914 @item %V
915 The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
916 through @code{53}).  ISO weeks start with Monday and end with Sunday.
917 Week @code{01} of a year is the first week which has the majority of its
918 days in that year; this is equivalent to the week containing the year's
919 first Thursday, and it is also equivalent to the week containing January
920 4.  Week @code{01} of a year can contain days from the previous year.
921 The week before week @code{01} of a year is the last week (@code{52} or
922 @code{53}) of the previous year even if it contains days from the new
923 year.
925 This format is a POSIX.2 extension.
927 @item %w
928 The day of the week as a decimal number (range @code{0} through
929 @code{6}), Sunday being @code{0}.
931 @item %W
932 The week number of the current year as a decimal number (range @code{00}
933 through @code{53}), starting with the first Monday as the first day of
934 the first week.  All days preceding the first Monday in the year are
935 considered to be in week @code{00}.
937 @item %x
938 The preferred date representation for the current locale, but without the
939 time.
941 @item %X
942 The preferred time representation for the current locale, but with no date.
944 @item %y
945 The year without a century as a decimal number (range @code{00} through
946 @code{99}).  This is equivalent to the year modulo 100.
948 @item %Y
949 The year as a decimal number, using the Gregorian calendar.  Years
950 before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
952 @item %z
953 @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
954 @code{-0600} or @code{+0100}), or nothing if no time zone is
955 determinable.
957 This format is a GNU extension.
959 A full @w{RFC 822} timestamp is generated by the format
960 @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
961 @w{@samp{"%a, %d %b %Y %T %z"}}).
963 @item %Z
964 The time zone abbreviation (empty if the time zone can't be determined).
966 @item %%
967 A literal @samp{%} character.
968 @end table
970 The @var{size} parameter can be used to specify the maximum number of
971 characters to be stored in the array @var{s}, including the terminating
972 null character.  If the formatted time requires more than @var{size}
973 characters, @code{strftime} returns zero and the content of the array
974 @var{s} is indetermined.  Otherwise the return value indicates the
975 number of characters placed in the array @var{s}, not including the
976 terminating null character.
978 @emph{Warning:} This convention for the return value which is prescribed
979 in @w{ISO C} can lead to problems in some situations.  For certain
980 format strings and certain locales the output really can be the empty
981 string and this cannot be discovered by testing the return value only.
982 E.g., in most locales the AM/PM time format is not supported (most of
983 the world uses the 24 hour time representation).  In such locales
984 @code{"%p"} will return the empty string, i.e., the return value is
985 zero.  To detect situations like this something similar to the following
986 code should be used:
988 @smallexample
989 buf[0] = '\1';
990 len = strftime (buf, bufsize, format, tp);
991 if (len == 0 && buf[0] != '\0')
992   @{
993     /* Something went wrong in the strftime call.  */
994     @dots{}
995   @}
996 @end smallexample
998 If @var{s} is a null pointer, @code{strftime} does not actually write
999 anything, but instead returns the number of characters it would have written.
1001 According to POSIX.1 every call to @code{strftime} implies a call to
1002 @code{tzset}.  So the contents of the environment variable @code{TZ}
1003 is examined before any output is produced.
1005 For an example of @code{strftime}, see @ref{Time Functions Example}.
1006 @end deftypefun
1008 @node Parsing Date and Time
1009 @subsection Convert textual time and date information back
1011 The @w{ISO C} standard does not specify any functions which can convert
1012 the output of the @code{strftime} function back into a binary format.
1013 This lead to variety of more or less successful implementations with
1014 different interfaces over the years.  Then the Unix standard got
1015 extended by two functions: @code{strptime} and @code{getdate}.  Both
1016 have kind of strange interfaces but at least they are widely available.
1018 @menu
1019 * Low-Level Time String Parsing::  Interpret string according to given format.
1020 * General Time String Parsing::    User-friendly function to parse data and
1021                                     time strings.
1022 @end menu
1024 @node Low-Level Time String Parsing
1025 @subsubsection Interpret string according to given format
1027 The first function is a rather low-level interface.  It is nevertheless
1028 frequently used in user programs since it is better known.  Its
1029 implementation and the interface though is heavily influenced by the
1030 @code{getdate} function which is defined and implemented in terms of
1031 calls to @code{strptime}.
1033 @comment time.h
1034 @comment XPG4
1035 @deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1036 The @code{strptime} function parses the input string @var{s} according
1037 to the format string @var{fmt} and stores the found values in the
1038 structure @var{tp}.
1040 The input string can be retrieved in any way.  It does not matter
1041 whether it was generated by a @code{strftime} call or made up directly
1042 by a program.  It is also not necessary that the content is in any
1043 human-recognizable format.  I.e., it is OK if a date is written like
1044 @code{"02:1999:9"} which is not understandable without context.  As long
1045 the format string @var{fmt} matches the format of the input string
1046 everything goes.
1048 The format string consists of the same components as the format string
1049 for the @code{strftime} function.  The only difference is that the flags
1050 @code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1051 @comment Is this really the intention?  --drepper
1052 Several of the formats which @code{strftime} handled differently do the
1053 same work in @code{strptime} since differences like case of the output
1054 do not matter.  For symmetry reasons all formats are supported, though.
1056 The modifiers @code{E} and @code{O} are also allowed everywhere the
1057 @code{strftime} function allows them.
1059 The formats are:
1061 @table @code
1062 @item %a
1063 @itemx %A
1064 The weekday name according to the current locale, in abbreviated form or
1065 the full name.
1067 @item %b
1068 @itemx %B
1069 @itemx %h
1070 The month name according to the current locale, in abbreviated form or
1071 the full name.
1073 @item %c
1074 The date and time representation for the current locale.
1076 @item %Ec
1077 Like @code{%c} but the locale's alternative date and time format is used.
1079 @item %C
1080 The century of the year.
1082 It makes sense to use this format only if the format string also
1083 contains the @code{%y} format.
1085 @item %EC
1086 The locale's representation of the period.
1088 Unlike @code{%C} it makes sometimes sense to use this format since in
1089 some cultures it is required to specify years relative to periods
1090 instead of using the Gregorian years.
1092 @item %d
1093 @item %e
1094 The day of the month as a decimal number (range @code{1} through @code{31}).
1095 Leading zeroes are permitted but not required.
1097 @item %Od
1098 @itemx %Oe
1099 Same as @code{%d} but the locale's alternative numeric symbols are used.
1101 Leading zeroes are permitted but not required.
1103 @item %D
1104 Equivalent to the use of @code{%m/%d/%y} in this place.
1106 @item %F
1107 Equivalent to the use of @code{%Y-%m-%d} which is the @w{ISO 8601} date
1108 format.
1110 This is a GNU extension following an @w{ISO C 9X} extension to
1111 @code{strftime}.
1113 @item %g
1114 The year corresponding to the ISO week number, but without the century
1115 (range @code{00} through @code{99}).
1117 @emph{Note:} This is not really implemented currently.  The format is
1118 recognized, input is consumed but no field in @var{tm} is set.
1120 This format is a GNU extension following a GNU extension of @code{strftime}.
1122 @item %G
1123 The year corresponding to the ISO week number.
1125 @emph{Note:} This is not really implemented currently.  The format is
1126 recognized, input is consumed but no field in @var{tm} is set.
1128 This format is a GNU extension following a GNU extension of @code{strftime}.
1130 @item %H
1131 @itemx %k
1132 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1133 @code{23}).
1135 @code{%k} is a GNU extension following a GNU extension of @code{strftime}.
1137 @item %OH
1138 Same as @code{%H} but using the locale's alternative numeric symbols are used.
1140 @item %I
1141 @itemx %l
1142 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1143 @code{12}).
1145 @code{%l} is a GNU extension following a GNU extension of @code{strftime}.
1147 @item %OI
1148 Same as @code{%I} but using the locale's alternative numeric symbols are used.
1150 @item %j
1151 The day of the year as a decimal number (range @code{1} through @code{366}).
1153 Leading zeroes are permitted but not required.
1155 @item %m
1156 The month as a decimal number (range @code{1} through @code{12}).
1158 Leading zeroes are permitted but not required.
1160 @item %Om
1161 Same as @code{%m} but using the locale's alternative numeric symbols are used.
1163 @item %M
1164 The minute as a decimal number (range @code{0} through @code{59}).
1166 Leading zeroes are permitted but not required.
1168 @item %OM
1169 Same as @code{%M} but using the locale's alternative numeric symbols are used.
1171 @item %n
1172 @itemx %t
1173 Matches any white space.
1175 @item %p
1176 @item %P
1177 The locale-dependent equivalent to @samp{AM} or @samp{PM}.
1179 This format is not useful unless @code{%I} or @code{%l} is also used.
1180 Another complication is that the locale might not define these values at
1181 all and therefore the conversion fails.
1183 @code{%P} is a GNU extension following a GNU extension to @code{strftime}.
1185 @item %r
1186 The complete time using the AM/PM format of the current locale.
1188 A complication is that the locale might not define this format at all
1189 and therefore the conversion fails.
1191 @item %R
1192 The hour and minute in decimal numbers using the format @code{%H:%M}.
1194 @code{%R} is a GNU extension following a GNU extension to @code{strftime}.
1196 @item %s
1197 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1198 Leap seconds are not counted unless leap second support is available.
1200 @code{%s} is a GNU extension following a GNU extension to @code{strftime}.
1202 @item %S
1203 The seconds as a decimal number (range @code{0} through @code{61}).
1205 Leading zeroes are permitted but not required.
1207 Please note the nonsense with @code{61} being allowed.  This is what the
1208 Unix specification says.  They followed the stupid decision once made to
1209 allow double leap seconds.  These do not exist but the myth persists.
1211 @item %OS
1212 Same as @code{%S} but using the locale's alternative numeric symbols are used.
1214 @item %T
1215 Equivalent to the use of @code{%H:%M:%S} in this place.
1217 @item %u
1218 The day of the week as a decimal number (range @code{1} through
1219 @code{7}), Monday being @code{1}.
1221 Leading zeroes are permitted but not required.
1223 @emph{Note:} This is not really implemented currently.  The format is
1224 recognized, input is consumed but no field in @var{tm} is set.
1226 @item %U
1227 The week number of the current year as a decimal number (range @code{0}
1228 through @code{53}).
1230 Leading zeroes are permitted but not required.
1232 @item %OU
1233 Same as @code{%U} but using the locale's alternative numeric symbols are used.
1235 @item %V
1236 The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
1237 through @code{53}).
1239 Leading zeroes are permitted but not required.
1241 @emph{Note:} This is not really implemented currently.  The format is
1242 recognized, input is consumed but no field in @var{tm} is set.
1244 @item %w
1245 The day of the week as a decimal number (range @code{0} through
1246 @code{6}), Sunday being @code{0}.
1248 Leading zeroes are permitted but not required.
1250 @emph{Note:} This is not really implemented currently.  The format is
1251 recognized, input is consumed but no field in @var{tm} is set.
1253 @item %Ow
1254 Same as @code{%w} but using the locale's alternative numeric symbols are used.
1256 @item %W
1257 The week number of the current year as a decimal number (range @code{0}
1258 through @code{53}).
1260 Leading zeroes are permitted but not required.
1262 @emph{Note:} This is not really implemented currently.  The format is
1263 recognized, input is consumed but no field in @var{tm} is set.
1265 @item %OW
1266 Same as @code{%W} but using the locale's alternative numeric symbols are used.
1268 @item %x
1269 The date using the locale's date format.
1271 @item %Ex
1272 Like @code{%x} but the locale's alternative data representation is used.
1274 @item %X
1275 The time using the locale's time format.
1277 @item %EX
1278 Like @code{%X} but the locale's alternative time representation is used.
1280 @item %y
1281 The year without a century as a decimal number (range @code{0} through
1282 @code{99}).
1284 Leading zeroes are permitted but not required.
1286 Please note that it is at least questionable to use this format without
1287 the @code{%C} format.  The @code{strptime} function does regard input
1288 values in the range @math{68} to @math{99} as the years @math{1969} to
1289 @math{1999} and the values @math{0} to @math{68} as the years
1290 @math{2000} to @math{2068}.  But maybe this heuristic fails for some
1291 input data.
1293 Therefore it is best to avoid @code{%y} completely and use @code{%Y}
1294 instead.
1296 @item %Ey
1297 The offset from @code{%EC} in the locale's alternative representation.
1299 @item %Oy
1300 The offset of the year (from @code{%C}) using the locale's alternative
1301 numeric symbols.
1303 @item %Y
1304 The year as a decimal number, using the Gregorian calendar.
1306 @item %EY
1307 The full alternative year representation.
1309 @item %z
1310 Equivalent to the use of @code{%a, %d %b %Y %H:%M:%S %z} in this place.
1311 This is the full @w{ISO 8601} date and time format.
1313 @item %Z
1314 The timezone name.
1316 @emph{Note:} This is not really implemented currently.  The format is
1317 recognized, input is consumed but no field in @var{tm} is set.
1319 @item %%
1320 A literal @samp{%} character.
1321 @end table
1323 All other characters in the format string must have a matching character
1324 in the input string.  Exceptions are white spaces in the input string
1325 which can match zero or more white space characters in the input string.
1327 The @code{strptime} function processes the input string from right to
1328 left.  Each of the three possible input elements (white space, literal,
1329 or format) are handled one after the other.  If the input cannot be
1330 matched to the format string the function stops.  The remainder of the
1331 format and input strings are not processed.
1333 The return value of the function is a pointer to the first character not
1334 processed in this function call.  In the case of an error the return
1335 value points to the first character not matched.  In case the input
1336 string contains more than required by the format string the return value
1337 points right after the last consumed input character.  In case the whole
1338 input string is consumed the return value points to the NUL byte at the
1339 end of the string.
1340 @end deftypefun
1342 The specification of the function in the XPG standard is rather vague.
1343 It leaves out a few important pieces of information.  Most important it
1344 does not specify what happens to those elements of @var{tm} which are
1345 not directly initialized by the different formats.  Various
1346 implementations on different Unix systems vary here.
1348 The GNU libc implementation does not touch those fields which are not
1349 directly initialized.  Exceptions are the @code{tm_wday} and
1350 @code{tm_yday} elements which are recomputed if any of the year, month,
1351 or date elements changed.  This has two implications:
1353 @itemize @bullet
1354 @item
1355 Before calling the @code{strptime} function for a new input string one
1356 has to prepare the structure passed in as the @var{tm}.  Normally this
1357 will mean that all values are initialized to zero.  Alternatively one
1358 can use all fields to values like @code{INT_MAX} which allows to
1359 determine which elements were set by the function call.  Zero does not
1360 work here since it is a valid value for many of the fields.
1362 Careful initialization is necessary if one wants to find out whether a
1363 certain field in @var{tm} was initialized by the function call.
1365 @item
1366 One can construct a @code{struct tm} value in several @code{strptime}
1367 calls in a row.  A useful application of this is for example the parsing
1368 of two separate strings, one containing the date information, the other
1369 the time information.  By parsing both one after the other without
1370 clearing the structure in between one can construct a complete
1371 broken-down time.
1372 @end itemize
1374 The following example shows a function which parses a string which is
1375 supposed to contain the date information in either US style or @w{ISO
1376 8601} form.
1378 @smallexample
1379 const char *
1380 parse_date (const char *input, struct tm *tm)
1382   const char *cp;
1384   /* @r{First clear the result structure.}  */
1385   memset (tm, '\0', sizeof (*tm));
1387   /* @r{Try the ISO format first.}  */
1388   cp = strptime (input, "%F", tm);
1389   if (cp == NULL)
1390     @{
1391       /* @r{Does not match.  Try the US form.}  */
1392       cp = strptime (input, "%D", tm);
1393     @}
1395   return cp;
1397 @end smallexample
1399 @node General Time String Parsing
1400 @subsubsection A user-friendlier way to parse times and dates
1402 The Unix standard defines another function to parse date strings.  The
1403 interface is, mildly said, weird.  But if this function fits into the
1404 application to be written it is just fine.  It is a problem when using
1405 this function in multi-threaded programs or in libraries since it
1406 returns a pointer to a static variable, uses a global variable, and a
1407 global state (an environment variable).
1409 @comment time.h
1410 @comment Unix98
1411 @defvar getdate_err
1412 This variable of type @code{int} will contain the error code of the last
1413 unsuccessful call of the @code{getdate} function.  Defined values are:
1415 @table @math
1416 @item 1
1417 The environment variable @code{DATEMSK} is not defined or null.
1418 @item 2
1419 The template file denoted by the @code{DATEMSK} environment variable
1420 cannot be opened.
1421 @item 3
1422 Information about the template file cannot retrieved.
1423 @item 4
1424 The template file is no regular file.
1425 @item 5
1426 An I/O error occurred while reading the template file.
1427 @item 6
1428 Not enough memory available to execute the function.
1429 @item 7
1430 The template file contains no matching template.
1431 @item 8
1432 The input string is invalid for a template which would match otherwise.
1433 This includes error like February 31st, or return values which can be
1434 represented using @code{time_t}.
1435 @end table
1436 @end defvar
1438 @comment time.h
1439 @comment Unix98
1440 @deftypefun {struct tm *} getdate (const char *@var{string})
1441 The interface of the @code{getdate} function is the simplest possible
1442 for a function to parse a string and return the value.  @var{string} is
1443 the input string and the result is passed to the user in a statically
1444 allocated variable.
1446 The details about how the string is processed is hidden from the user.
1447 In fact, it can be outside the control of the program.  Which formats
1448 are recognized is controlled by the file named by the environment
1449 variable @code{DATEMSK}.  The content of the named file should contain
1450 lines of valid format strings which could be passed to @code{strptime}.
1452 The @code{getdate} function reads these format strings one after the
1453 other and tries to match the input string.  The first line which
1454 completely matches the input string is used.
1456 Elements which were not initialized through the format string get
1457 assigned the values of the time the @code{getdate} function is called.
1459 The format elements recognized by @code{getdate} are the same as for
1460 @code{strptime}.  See above for an explanation.  There are only a few
1461 extension to the @code{strptime} behavior:
1463 @itemize @bullet
1464 @item
1465 If the @code{%Z} format is given the broken-down time is based on the
1466 current time in the timezone matched, not in the current timezone of the
1467 runtime environment.
1469 @emph{Note}: This is not implemented (currently).  The problem is that
1470 timezone names are not unique.  If a fixed timezone is assumed for a
1471 given string (say @code{EST} meaning US East Coast time) uses for
1472 countries other than the USA will fail.  So far we have found no good
1473 solution for this.
1475 @item
1476 If only the weekday is specified the selected day depends on the current
1477 date.  If the current weekday is greater or equal to the @code{tm_wday}
1478 value this weeks day is selected.  Otherwise next weeks day.
1480 @item
1481 A similar heuristic is used if only the month is given, not the year.
1482 For value corresponding to the current or a later month the current year
1483 s used.  Otherwise the next year.  The first day of the month is assumed
1484 if it is not explicitly specified.
1486 @item
1487 The current hour, minute, and second is used if the appropriate value is
1488 not set through the format.
1490 @item
1491 If no date is given the date for the next day is used if the time is
1492 smaller than the current time.  Otherwise it is the same day.
1493 @end itemize
1495 It should be noted that the format in the template file need not only
1496 contain format elements.  The following is a list of possible format
1497 strings (taken from the Unix standard):
1499 @smallexample
1501 %A %B %d, %Y %H:%M:%S
1504 %m/%d/%y %I %p
1505 %d,%m,%Y %H:%M
1506 at %A the %dst of %B in %Y
1507 run job at %I %p,%B %dnd
1508 %A den %d. %B %Y %H.%M Uhr
1509 @end smallexample
1511 As one can see the template list can contain very specific strings like
1512 @code{run job at %I %p,%B %dnd}.  Using the above list of templates and
1513 assuming the current time is Mon Sep 22 12:19:47 EDT 1986 we can get the
1514 The results for the given input.
1516 @multitable {xxxxxxxxxxxx} {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1517 @item        Mon @tab       %a @tab    Mon Sep 22 12:19:47 EDT 1986
1518 @item        Sun @tab       %a @tab    Sun Sep 28 12:19:47 EDT 1986
1519 @item        Fri @tab       %a @tab    Fri Sep 26 12:19:47 EDT 1986
1520 @item        September @tab %B @tab    Mon Sep 1 12:19:47 EDT 1986
1521 @item        January @tab   %B @tab    Thu Jan 1 12:19:47 EST 1987
1522 @item        December @tab  %B @tab    Mon Dec 1 12:19:47 EST 1986
1523 @item        Sep Mon @tab   %b %a @tab Mon Sep 1 12:19:47 EDT 1986
1524 @item        Jan Fri @tab   %b %a @tab Fri Jan 2 12:19:47 EST 1987
1525 @item        Dec Mon @tab   %b %a @tab Mon Dec 1 12:19:47 EST 1986
1526 @item        Jan Wed 1989 @tab  %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
1527 @item        Fri 9 @tab     %a %H @tab Fri Sep 26 09:00:00 EDT 1986
1528 @item        Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
1529 @item        10:30 @tab     %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
1530 @item        13:30 @tab     %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
1531 @end multitable
1533 The return value of the function is a pointer to a static variable of
1534 type @w{@code{struct tm}} or a null pointer if an error occurred.  The
1535 result in the variable pointed to by the return value is only valid
1536 until the next @code{getdate} call which makes this function unusable in
1537 multi-threaded applications.
1539 The @code{errno} variable is @emph{not} changed.  Error conditions are
1540 signalled using the global variable @code{getdate_err}.  See the
1541 description above for a list of the possible error values.
1543 @emph{Warning:} The @code{getdate} function should @emph{never} be
1544 used in SUID-programs.  The reason is obvious: using the
1545 @code{DATEMSK} environment variable one can get the function to open
1546 any arbitrary file and changes are high that with some bogus input
1547 (such as a binary file) the program will crash.
1548 @end deftypefun
1550 @comment time.h
1551 @comment GNU
1552 @deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
1553 The @code{getdate_r} function is the reentrant counterpart of
1554 @code{getdate}.  It does not use the global variable @code{getdate_err}
1555 to signal the error but instead the return value now is this error code.
1556 The same error codes as described in the @code{getdate_err}
1557 documentation above are used.
1559 @code{getdate_r} also does not store the broken-down time in a static
1560 variable.  Instead it takes an second argument which must be a pointer
1561 to a variable of type @code{struct tm} where the broken-down can be
1562 stored.
1564 This function is not defined in the Unix standard.  Nevertheless it is
1565 available on some other Unix systems as well.
1567 As for @code{getdate} the warning for using this function in
1568 SUID-programs applies to @code{getdate_r} as well.
1569 @end deftypefun
1571 @node TZ Variable
1572 @subsection Specifying the Time Zone with @code{TZ}
1574 In POSIX systems, a user can specify the time zone by means of the
1575 @code{TZ} environment variable.  For information about how to set
1576 environment variables, see @ref{Environment Variables}.  The functions
1577 for accessing the time zone are declared in @file{time.h}.
1578 @pindex time.h
1579 @cindex time zone
1581 You should not normally need to set @code{TZ}.  If the system is
1582 configured properly, the default time zone will be correct.  You might
1583 set @code{TZ} if you are using a computer over the network from a
1584 different time zone, and would like times reported to you in the time zone
1585 that local for you, rather than what is local for the computer.
1587 In POSIX.1 systems the value of the @code{TZ} variable can be of one of
1588 three formats.  With the GNU C library, the most common format is the
1589 last one, which can specify a selection from a large database of time
1590 zone information for many regions of the world.  The first two formats
1591 are used to describe the time zone information directly, which is both
1592 more cumbersome and less precise.  But the POSIX.1 standard only
1593 specifies the details of the first two formats, so it is good to be
1594 familiar with them in case you come across a POSIX.1 system that doesn't
1595 support a time zone information database.
1597 The first format is used when there is no Daylight Saving Time (or
1598 summer time) in the local time zone:
1600 @smallexample
1601 @r{@var{std} @var{offset}}
1602 @end smallexample
1604 The @var{std} string specifies the name of the time zone.  It must be
1605 three or more characters long and must not contain a leading colon or
1606 embedded digits, commas, or plus or minus signs.  There is no space
1607 character separating the time zone name from the @var{offset}, so these
1608 restrictions are necessary to parse the specification correctly.
1610 The @var{offset} specifies the time value one must add to the local time
1611 to get a Coordinated Universal Time value.  It has syntax like
1612 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]].  This
1613 is positive if the local time zone is west of the Prime Meridian and
1614 negative if it is east.  The hour must be between @code{0} and
1615 @code{23}, and the minute and seconds between @code{0} and @code{59}.
1617 For example, here is how we would specify Eastern Standard Time, but
1618 without any daylight saving time alternative:
1620 @smallexample
1621 EST+5
1622 @end smallexample
1624 The second format is used when there is Daylight Saving Time:
1626 @smallexample
1627 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
1628 @end smallexample
1630 The initial @var{std} and @var{offset} specify the standard time zone, as
1631 described above.  The @var{dst} string and @var{offset} specify the name
1632 and offset for the corresponding daylight saving time zone; if the
1633 @var{offset} is omitted, it defaults to one hour ahead of standard time.
1635 The remainder of the specification describes when daylight saving time is
1636 in effect.  The @var{start} field is when daylight saving time goes into
1637 effect and the @var{end} field is when the change is made back to standard
1638 time.  The following formats are recognized for these fields:
1640 @table @code
1641 @item J@var{n}
1642 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
1643 February 29 is never counted, even in leap years.
1645 @item @var{n}
1646 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
1647 February 29 is counted in leap years.
1649 @item M@var{m}.@var{w}.@var{d}
1650 This specifies day @var{d} of week @var{w} of month @var{m}.  The day
1651 @var{d} must be between @code{0} (Sunday) and @code{6}.  The week
1652 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
1653 first week in which day @var{d} occurs, and week @code{5} specifies the
1654 @emph{last} @var{d} day in the month.  The month @var{m} should be
1655 between @code{1} and @code{12}.
1656 @end table
1658 The @var{time} fields specify when, in the local time currently in
1659 effect, the change to the other time occurs.  If omitted, the default is
1660 @code{02:00:00}.
1662 For example, here is how one would specify the Eastern time zone in the
1663 United States, including the appropriate daylight saving time and its dates
1664 of applicability.  The normal offset from UTC is 5 hours; since this is
1665 west of the prime meridian, the sign is positive.  Summer time begins on
1666 the first Sunday in April at 2:00am, and ends on the last Sunday in October
1667 at 2:00am.
1669 @smallexample
1670 EST+5EDT,M4.1.0/2,M10.5.0/2
1671 @end smallexample
1673 The schedule of daylight saving time in any particular jurisdiction has
1674 changed over the years.  To be strictly correct, the conversion of dates
1675 and times in the past should be based on the schedule that was in effect
1676 then.  However, this format has no facilities to let you specify how the
1677 schedule has changed from year to year.  The most you can do is specify
1678 one particular schedule---usually the present day schedule---and this is
1679 used to convert any date, no matter when.  For precise time zone
1680 specifications, it is best to use the time zone information database
1681 (see below).
1683 The third format looks like this:
1685 @smallexample
1686 :@var{characters}
1687 @end smallexample
1689 Each operating system interprets this format differently; in the GNU C
1690 library, @var{characters} is the name of a file which describes the time
1691 zone.
1693 @pindex /etc/localtime
1694 @pindex localtime
1695 If the @code{TZ} environment variable does not have a value, the
1696 operation chooses a time zone by default.  In the GNU C library, the
1697 default time zone is like the specification @samp{TZ=:/etc/localtime}
1698 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how GNU C library
1699 was configured; @pxref{Installation}).  Other C libraries use their own
1700 rule for choosing the default time zone, so there is little we can say
1701 about them.
1703 @cindex time zone database
1704 @pindex /share/lib/zoneinfo
1705 @pindex zoneinfo
1706 If @var{characters} begins with a slash, it is an absolute file name;
1707 otherwise the library looks for the file
1708 @w{@file{/share/lib/zoneinfo/@var{characters}}}.  The @file{zoneinfo}
1709 directory contains data files describing local time zones in many
1710 different parts of the world.  The names represent major cities, with
1711 subdirectories for geographical areas; for example,
1712 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
1713 These data files are installed by the system administrator, who also
1714 sets @file{/etc/localtime} to point to the data file for the local time
1715 zone.  The GNU C library comes with a large database of time zone
1716 information for most regions of the world, which is maintained by a
1717 community of volunteers and put in the public domain.
1719 @node Time Zone Functions
1720 @subsection Functions and Variables for Time Zones
1722 @comment time.h
1723 @comment POSIX.1
1724 @deftypevar {char *} tzname [2]
1725 The array @code{tzname} contains two strings, which are the standard
1726 names of the pair of time zones (standard and daylight
1727 saving) that the user has selected.  @code{tzname[0]} is the name of
1728 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
1729 is the name for the time zone when daylight saving time is in use (for
1730 example, @code{"EDT"}).  These correspond to the @var{std} and @var{dst}
1731 strings (respectively) from the @code{TZ} environment variable.  If
1732 daylight saving time is never used, @code{tzname[1]} is the empty string.
1734 The @code{tzname} array is initialized from the @code{TZ} environment
1735 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
1736 @code{mktime}, or @code{localtime} is called.  If multiple abbreviations
1737 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
1738 Time and Eastern Daylight Time), the array contains the most recent
1739 abbreviation.
1741 The @code{tzname} array is required for POSIX.1 compatibility, but in
1742 GNU programs it is better to use the @code{tm_zone} member of the
1743 broken-down time structure, since @code{tm_zone} reports the correct
1744 abbreviation even when it is not the latest one.
1746 Though the strings are declared as @code{char *} the user must stay away
1747 from modifying these strings.  Modifying the strings will almost certainly
1748 lead to trouble.
1750 @end deftypevar
1752 @comment time.h
1753 @comment POSIX.1
1754 @deftypefun void tzset (void)
1755 The @code{tzset} function initializes the @code{tzname} variable from
1756 the value of the @code{TZ} environment variable.  It is not usually
1757 necessary for your program to call this function, because it is called
1758 automatically when you use the other time conversion functions that
1759 depend on the time zone.
1760 @end deftypefun
1762 The following variables are defined for compatibility with System V
1763 Unix.  Like @code{tzname}, these variables are set by calling
1764 @code{tzset} or the other time conversion functions.
1766 @comment time.h
1767 @comment SVID
1768 @deftypevar {long int} timezone
1769 This contains the difference between UTC and the latest local standard
1770 time, in seconds west of UTC.  For example, in the U.S. Eastern time
1771 zone, the value is @code{5*60*60}.  Unlike the @code{tm_gmtoff} member
1772 of the broken-down time structure, this value is not adjusted for
1773 daylight saving, and its sign is reversed.  In GNU programs it is better
1774 to use @code{tm_gmtoff}, since it contains the correct offset even when
1775 it is not the latest one.
1776 @end deftypevar
1778 @comment time.h
1779 @comment SVID
1780 @deftypevar int daylight
1781 This variable has a nonzero value if daylight savings time rules apply.
1782 A nonzero value does not necessarily mean that daylight savings time is
1783 now in effect; it means only that daylight savings time is sometimes in
1784 effect.
1785 @end deftypevar
1787 @node Time Functions Example
1788 @subsection Time Functions Example
1790 Here is an example program showing the use of some of the local time and
1791 calendar time functions.
1793 @smallexample
1794 @include strftim.c.texi
1795 @end smallexample
1797 It produces output like this:
1799 @smallexample
1800 Wed Jul 31 13:02:36 1991
1801 Today is Wednesday, July 31.
1802 The time is 01:02 PM.
1803 @end smallexample
1806 @node Precision Time
1807 @section Precision Time
1809 @cindex time, high precision
1810 @pindex sys/timex.h
1811 The @code{net_gettime} and @code{ntp_adjtime} functions provide an
1812 interface to monitor and manipulate high precision time.  These
1813 functions are declared in @file{sys/timex.h}.
1815 @tindex struct ntptimeval
1816 @deftp {Data Type} {struct ntptimeval}
1817 This structure is used to monitor kernel time.  It contains the
1818 following members:
1819 @table @code
1820 @item struct timeval time
1821 This is the current time.  The @code{struct timeval} data type is
1822 described in @ref{High-Resolution Calendar}.
1824 @item long int maxerror
1825 This is the maximum error, measured in microseconds.  Unless updated
1826 via @code{ntp_adjtime} periodically, this value will reach some
1827 platform-specific maximum value.
1829 @item long int esterror
1830 This is the estimated error, measured in microseconds.  This value can
1831 be set by @code{ntp_adjtime} to indicate the estimated offset of the
1832 local clock against the true time.
1833 @end table
1834 @end deftp
1836 @comment sys/timex,h
1837 @comment GNU
1838 @deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
1839 The @code{ntp_gettime} function sets the structure pointed to by
1840 @var{tptr} to current values.  The elements of the structure afterwards
1841 contain the values the timer implementation in the kernel assumes.  They
1842 might or might not be correct.  If they are not a @code{ntp_adjtime}
1843 call is necessary.
1845 The return value is @code{0} on success and other values on failure.  The
1846 following @code{errno} error conditions are defined for this function:
1848 @table @code
1849 @item TIME_ERROR
1850 The precision clock model is not properly set up at the moment, thus the
1851 clock must be considered unsynchronized, and the values should be
1852 treated with care.
1853 @end table
1854 @end deftypefun
1856 @tindex struct timex
1857 @deftp {Data Type} {struct timex}
1858 This structure is used to control and monitor kernel time in a greater
1859 level of detail.  It contains the following members:
1860 @table @code
1861 @item unsigned int mode
1862 This variable controls whether and which values are set.  Several
1863 symbolic constants have to be combined with @emph{binary or} to specify
1864 the effective mode.  These constants start with @code{MOD_}.
1866 @item long int offset
1867 This value indicates the current offset of the local clock from the true
1868 time.  The value is given in microseconds.  If bit @code{MOD_OFFSET} is
1869 set in @code{mode}, the offset (and possibly other dependent values) can
1870 be set.  The offset's absolute value must not exceed @code{MAXPHASE}.
1872 @item long int frequency
1873 This value indicates the difference in frequency between the true time
1874 and the local clock.  The value is expressed as scaled PPM (parts per
1875 million, 0.0001%).  The scaling is @code{1 << SHIFT_USEC}.  The value
1876 can be set with bit @code{MOD_FREQUENCY}, but the absolute value must
1877 not exceed @code{MAXFREQ}.
1879 @item long int maxerror
1880 This is the maximum error, measured in microseconds.  A new value can be
1881 set using bit @code{MOD_MAXERROR}.  Unless updated via
1882 @code{ntp_adjtime} periodically, this value will increase steadily
1883 and reach some platform-specific maximum value.
1885 @item long int esterror
1886 This is the estimated error, measured in microseconds.  This value can
1887 be set using bit @code{MOD_ESTERROR}.
1889 @item int status
1890 This valiable reflects the various states of the clock machinery.  There
1891 are symbolic constants for the significant bits, starting with
1892 @code{STA_}.  Some of these flags can be updated using the
1893 @code{MOD_STATUS} bit.
1895 @item long int constant
1896 This value represents the bandwidth or stiffness of the PLL (phase
1897 locked loop) implemented in the kernel.  The value can be changed using
1898 bit @code{MOD_TIMECONST}.
1900 @item long int precision
1901 This value represents the accuracy or the maximum error when reading the
1902 system clock.  The value is expressed in microseconds and can't be changed.
1904 @item long int tolerance
1905 This value represents the maximum frequency error of the system clock in
1906 scaled PPM.  This value is used to increase the @code{maxerror} every
1907 second.
1909 @item long int ppsfreq
1910 This is the first of a few optional variables that are present only if
1911 the system clock can use a PPS (pulse per second) signal to discipline
1912 the local clock.  The value is expressed in scaled PPM and it denotes
1913 the difference in frequency between the local clock and the PPS signal.
1915 @item long int jitter
1916 This value expresses a median filtered average of the PPS signal's
1917 dispersion in microseconds.
1919 @item int int shift
1920 This value is a binary exponent for the duration of the PPS calibration
1921 interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
1923 @item long int stabil
1924 This value represents the median filtered dispersion of the PPS
1925 frequency in scaled PPM.
1927 @item long int jitcnt
1928 This counter represents the numer of pulses where the jitter exceeded
1929 the allowed maximum @code{MAXTIME}.
1931 @item long int calcnt
1932 This counter reflects the number of successful calibration intervals.
1934 @item long int errcnt
1935 This counter represents the number of calibration errors (caused by
1936 large offsets or jitter).
1938 @item long int stbcnt
1939 This counter denotes the number of of calibrations where the stability
1940 exceeded the threshold.
1941 @end table
1942 @end deftp
1944 @comment sys/timex.h
1945 @comment GNU
1946 @deftypefun int ntp_adjtime (int @var{mode}, struct timex *@var{tptr})
1947 The @code{ntp_adjtime} function sets the structure specified by
1948 @var{tptr} to current values.  In addition, values passed in @var{tptr}
1949 can be used to replace existing settings.  Therefore several magic
1950 values can be passed in @var{mode}.  Setting @var{mode} to zero only
1951 reads the current state.
1953 The return value is @code{0} on success and other values on failure.  The
1954 following @code{errno} error conditions are defined for this function:
1956 @table @code
1957 @item TIME_ERROR
1958 The precision clock model is not properly set up at the moment, thus the
1959 clock must be considered unsynchronized, and the values should be
1960 treated with care.  Another reason could be that the specified new values
1961 are not allowed.
1962 @end table
1964 For more details see RFC1305 (Network Time Protocol, Version 3) and
1965 related documents.
1966 @end deftypefun
1969 @node Setting an Alarm
1970 @section Setting an Alarm
1972 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
1973 process to interrupt itself at some future time.  They do this by setting a
1974 timer; when the timer expires, the process receives a signal.
1976 @cindex setting an alarm
1977 @cindex interval timer, setting
1978 @cindex alarms, setting
1979 @cindex timers, setting
1980 Each process has three independent interval timers available:
1982 @itemize @bullet
1983 @item
1984 A real-time timer that counts clock time.  This timer sends a
1985 @code{SIGALRM} signal to the process when it expires.
1986 @cindex real-time timer
1987 @cindex timer, real-time
1989 @item
1990 A virtual timer that counts CPU time used by the process.  This timer
1991 sends a @code{SIGVTALRM} signal to the process when it expires.
1992 @cindex virtual timer
1993 @cindex timer, virtual
1995 @item
1996 A profiling timer that counts both CPU time used by the process, and CPU
1997 time spent in system calls on behalf of the process.  This timer sends a
1998 @code{SIGPROF} signal to the process when it expires.
1999 @cindex profiling timer
2000 @cindex timer, profiling
2002 This timer is useful for profiling in interpreters.  The interval timer
2003 mechanism does not have the fine granularity necessary for profiling
2004 native code.
2005 @c @xref{profil} !!!
2006 @end itemize
2008 You can only have one timer of each kind set at any given time.  If you
2009 set a timer that has not yet expired, that timer is simply reset to the
2010 new value.
2012 You should establish a handler for the appropriate alarm signal using
2013 @code{signal} or @code{sigaction} before issuing a call to @code{setitimer}
2014 or @code{alarm}.  Otherwise, an unusual chain of events could cause the
2015 timer to expire before your program establishes the handler, and in that
2016 case it would be terminated, since that is the default action for the alarm
2017 signals.  @xref{Signal Handling}.
2019 The @code{setitimer} function is the primary means for setting an alarm.
2020 This facility is declared in the header file @file{sys/time.h}.  The
2021 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
2022 simpler interface for setting the real-time timer.
2023 @pindex unistd.h
2024 @pindex sys/time.h
2026 @comment sys/time.h
2027 @comment BSD
2028 @deftp {Data Type} {struct itimerval}
2029 This structure is used to specify when a timer should expire.  It contains
2030 the following members:
2031 @table @code
2032 @item struct timeval it_interval
2033 This is the interval between successive timer interrupts.  If zero, the
2034 alarm will only be sent once.
2036 @item struct timeval it_value
2037 This is the interval to the first timer interrupt.  If zero, the alarm is
2038 disabled.
2039 @end table
2041 The @code{struct timeval} data type is described in @ref{High-Resolution
2042 Calendar}.
2043 @end deftp
2045 @comment sys/time.h
2046 @comment BSD
2047 @deftypefun int setitimer (int @var{which}, struct itimerval *@var{new}, struct itimerval *@var{old})
2048 The @code{setitimer} function sets the timer specified by @var{which}
2049 according to @var{new}.  The @var{which} argument can have a value of
2050 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
2052 If @var{old} is not a null pointer, @code{setitimer} returns information
2053 about any previous unexpired timer of the same kind in the structure it
2054 points to.
2056 The return value is @code{0} on success and @code{-1} on failure.  The
2057 following @code{errno} error conditions are defined for this function:
2059 @table @code
2060 @item EINVAL
2061 The timer interval was too large.
2062 @end table
2063 @end deftypefun
2065 @comment sys/time.h
2066 @comment BSD
2067 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
2068 The @code{getitimer} function stores information about the timer specified
2069 by @var{which} in the structure pointed at by @var{old}.
2071 The return value and error conditions are the same as for @code{setitimer}.
2072 @end deftypefun
2074 @comment sys/time.h
2075 @comment BSD
2076 @table @code
2077 @item ITIMER_REAL
2078 @findex ITIMER_REAL
2079 This constant can be used as the @var{which} argument to the
2080 @code{setitimer} and @code{getitimer} functions to specify the real-time
2081 timer.
2083 @comment sys/time.h
2084 @comment BSD
2085 @item ITIMER_VIRTUAL
2086 @findex ITIMER_VIRTUAL
2087 This constant can be used as the @var{which} argument to the
2088 @code{setitimer} and @code{getitimer} functions to specify the virtual
2089 timer.
2091 @comment sys/time.h
2092 @comment BSD
2093 @item ITIMER_PROF
2094 @findex ITIMER_PROF
2095 This constant can be used as the @var{which} argument to the
2096 @code{setitimer} and @code{getitimer} functions to specify the profiling
2097 timer.
2098 @end table
2100 @comment unistd.h
2101 @comment POSIX.1
2102 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
2103 The @code{alarm} function sets the real-time timer to expire in
2104 @var{seconds} seconds.  If you want to cancel any existing alarm, you
2105 can do this by calling @code{alarm} with a @var{seconds} argument of
2106 zero.
2108 The return value indicates how many seconds remain before the previous
2109 alarm would have been sent.  If there is no previous alarm, @code{alarm}
2110 returns zero.
2111 @end deftypefun
2113 The @code{alarm} function could be defined in terms of @code{setitimer}
2114 like this:
2116 @smallexample
2117 unsigned int
2118 alarm (unsigned int seconds)
2120   struct itimerval old, new;
2121   new.it_interval.tv_usec = 0;
2122   new.it_interval.tv_sec = 0;
2123   new.it_value.tv_usec = 0;
2124   new.it_value.tv_sec = (long int) seconds;
2125   if (setitimer (ITIMER_REAL, &new, &old) < 0)
2126     return 0;
2127   else
2128     return old.it_value.tv_sec;
2130 @end smallexample
2132 There is an example showing the use of the @code{alarm} function in
2133 @ref{Handler Returns}.
2135 If you simply want your process to wait for a given number of seconds,
2136 you should use the @code{sleep} function.  @xref{Sleeping}.
2138 You shouldn't count on the signal arriving precisely when the timer
2139 expires.  In a multiprocessing environment there is typically some
2140 amount of delay involved.
2142 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
2143 functions are derived from BSD Unix, while the @code{alarm} function is
2144 specified by the POSIX.1 standard.  @code{setitimer} is more powerful than
2145 @code{alarm}, but @code{alarm} is more widely used.
2147 @node Sleeping
2148 @section Sleeping
2150 The function @code{sleep} gives a simple way to make the program wait
2151 for short periods of time.  If your program doesn't use signals (except
2152 to terminate), then you can expect @code{sleep} to wait reliably for
2153 the specified amount of time.  Otherwise, @code{sleep} can return sooner
2154 if a signal arrives; if you want to wait for a given period regardless
2155 of signals, use @code{select} (@pxref{Waiting for I/O}) and don't
2156 specify any descriptors to wait for.
2157 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
2159 @comment unistd.h
2160 @comment POSIX.1
2161 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
2162 The @code{sleep} function waits for @var{seconds} or until a signal
2163 is delivered, whichever happens first.
2165 If @code{sleep} function returns because the requested time has
2166 elapsed, it returns a value of zero.  If it returns because of delivery
2167 of a signal, its return value is the remaining time in the sleep period.
2169 The @code{sleep} function is declared in @file{unistd.h}.
2170 @end deftypefun
2172 Resist the temptation to implement a sleep for a fixed amount of time by
2173 using the return value of @code{sleep}, when nonzero, to call
2174 @code{sleep} again.  This will work with a certain amount of accuracy as
2175 long as signals arrive infrequently.  But each signal can cause the
2176 eventual wakeup time to be off by an additional second or so.  Suppose a
2177 few signals happen to arrive in rapid succession by bad luck---there is
2178 no limit on how much this could shorten or lengthen the wait.
2180 Instead, compute the time at which the program should stop waiting, and
2181 keep trying to wait until that time.  This won't be off by more than a
2182 second.  With just a little more work, you can use @code{select} and
2183 make the waiting period quite accurate.  (Of course, heavy system load
2184 can cause unavoidable additional delays---unless the machine is
2185 dedicated to one application, there is no way you can avoid this.)
2187 On some systems, @code{sleep} can do strange things if your program uses
2188 @code{SIGALRM} explicitly.  Even if @code{SIGALRM} signals are being
2189 ignored or blocked when @code{sleep} is called, @code{sleep} might
2190 return prematurely on delivery of a @code{SIGALRM} signal.  If you have
2191 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
2192 signal is delivered while the process is sleeping, the action taken
2193 might be just to cause @code{sleep} to return instead of invoking your
2194 handler.  And, if @code{sleep} is interrupted by delivery of a signal
2195 whose handler requests an alarm or alters the handling of @code{SIGALRM},
2196 this handler and @code{sleep} will interfere.
2198 On the GNU system, it is safe to use @code{sleep} and @code{SIGALRM} in
2199 the same program, because @code{sleep} does not work by means of
2200 @code{SIGALRM}.
2202 @comment time.h
2203 @comment POSIX.1
2204 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
2205 If the resolution of seconds is not enough the @code{nanosleep} function
2206 can be used.  As the name suggests the sleeping period can be specified
2207 in nanoseconds.  The actual period of waiting time might be longer since
2208 the requested time in the @var{requested_time} parameter is rounded up
2209 to the next integer multiple of the actual resolution of the system.
2211 If the function returns because the time has elapsed the return value is
2212 zero.  If the function return @math{-1} the global variable @var{errno}
2213 is set to the following values:
2215 @table @code
2216 @item EINTR
2217 The call was interrupted because a signal was delivered to the thread.
2218 If the @var{remaining} parameter is not the null pointer the structure
2219 pointed to by @var{remaining} is updated to contain the remaining time.
2221 @item EINVAL
2222 The nanosecond value in the @var{requested_time} parameter contains an
2223 illegal value.  Either the value is negative or greater than or equal to
2224 1000 million.
2225 @end table
2227 This function is a cancelation point in multi-threaded programs.  This
2228 is a problem if the thread allocates some resources (like memory, file
2229 descriptors, semaphores or whatever) at the time @code{nanosleep} is
2230 called.  If the thread gets canceled these resources stay allocated
2231 until the program ends.  To avoid this calls to @code{nanosleep} should
2232 be protected using cancelation handlers.
2233 @c ref pthread_cleanup_push / pthread_cleanup_pop
2235 The @code{nanosleep} function is declared in @file{time.h}.
2236 @end deftypefun
2238 @node Resource Usage
2239 @section Resource Usage
2241 @pindex sys/resource.h
2242 The function @code{getrusage} and the data type @code{struct rusage}
2243 are used for examining the usage figures of a process.  They are declared
2244 in @file{sys/resource.h}.
2246 @comment sys/resource.h
2247 @comment BSD
2248 @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
2249 This function reports the usage totals for processes specified by
2250 @var{processes}, storing the information in @code{*@var{rusage}}.
2252 In most systems, @var{processes} has only two valid values:
2254 @table @code
2255 @comment sys/resource.h
2256 @comment BSD
2257 @item RUSAGE_SELF
2258 Just the current process.
2260 @comment sys/resource.h
2261 @comment BSD
2262 @item RUSAGE_CHILDREN
2263 All child processes (direct and indirect) that have terminated already.
2264 @end table
2266 In the GNU system, you can also inquire about a particular child process
2267 by specifying its process ID.
2269 The return value of @code{getrusage} is zero for success, and @code{-1}
2270 for failure.
2272 @table @code
2273 @item EINVAL
2274 The argument @var{processes} is not valid.
2275 @end table
2276 @end deftypefun
2278 One way of getting usage figures for a particular child process is with
2279 the function @code{wait4}, which returns totals for a child when it
2280 terminates.  @xref{BSD Wait Functions}.
2282 @comment sys/resource.h
2283 @comment BSD
2284 @deftp {Data Type} {struct rusage}
2285 This data type records a collection usage amounts for various sorts of
2286 resources.  It has the following members, and possibly others:
2288 @table @code
2289 @item struct timeval ru_utime
2290 Time spent executing user instructions.
2292 @item struct timeval ru_stime
2293 Time spent in operating system code on behalf of @var{processes}.
2295 @item long int ru_maxrss
2296 The maximum resident set size used, in kilobytes.  That is, the maximum
2297 number of kilobytes that @var{processes} used in real memory simultaneously.
2299 @item long int ru_ixrss
2300 An integral value expressed in kilobytes times ticks of execution, which
2301 indicates the amount of memory used by text that was shared with other
2302 processes.
2304 @item long int ru_idrss
2305 An integral value expressed the same way, which is the amount of
2306 unshared memory used in data.
2308 @item long int ru_isrss
2309 An integral value expressed the same way, which is the amount of
2310 unshared memory used in stack space.
2312 @item long int ru_minflt
2313 The number of page faults which were serviced without requiring any I/O.
2315 @item long int ru_majflt
2316 The number of page faults which were serviced by doing I/O.
2318 @item long int ru_nswap
2319 The number of times @var{processes} was swapped entirely out of main memory.
2321 @item long int ru_inblock
2322 The number of times the file system had to read from the disk on behalf
2323 of @var{processes}.
2325 @item long int ru_oublock
2326 The number of times the file system had to write to the disk on behalf
2327 of @var{processes}.
2329 @item long int ru_msgsnd
2330 Number of IPC messages sent.
2332 @item long ru_msgrcv
2333 Number of IPC messages received.
2335 @item long int ru_nsignals
2336 Number of signals received.
2338 @item long int ru_nvcsw
2339 The number of times @var{processes} voluntarily invoked a context switch
2340 (usually to wait for some service).
2342 @item long int ru_nivcsw
2343 The number of times an involuntary context switch took place (because
2344 the time slice expired, or another process of higher priority became
2345 runnable).
2346 @end table
2347 @end deftp
2349 An additional historical function for examining usage figures,
2350 @code{vtimes}, is supported but not documented here.  It is declared in
2351 @file{sys/vtimes.h}.
2353 @node Limits on Resources
2354 @section Limiting Resource Usage
2355 @cindex resource limits
2356 @cindex limits on resource usage
2357 @cindex usage limits
2359 You can specify limits for the resource usage of a process.  When the
2360 process tries to exceed a limit, it may get a signal, or the system call
2361 by which it tried to do so may fail, depending on the limit.  Each
2362 process initially inherits its limit values from its parent, but it can
2363 subsequently change them.
2365 @pindex sys/resource.h
2366 The symbols in this section are defined in @file{sys/resource.h}.
2368 @comment sys/resource.h
2369 @comment BSD
2370 @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
2371 Read the current value and the maximum value of resource @var{resource}
2372 and store them in @code{*@var{rlp}}.
2374 The return value is @code{0} on success and @code{-1} on failure.  The
2375 only possible @code{errno} error condition is @code{EFAULT}.
2377 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
2378 32 bits system this function is in fact @code{getrlimit64}.  I.e., the
2379 LFS interface transparently replaces the old interface.
2380 @end deftypefun
2382 @comment sys/resource.h
2383 @comment Unix98
2384 @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
2385 This function is similar to the @code{getrlimit} but its second
2386 parameter is a pointer to a variable of type @code{struct rlimit64}
2387 which allows this function to read values which wouldn't fit in the
2388 member of a @code{struct rlimit}.
2390 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
2391 bits machine this function is available under the name @code{getrlimit}
2392 and so transparently replaces the old interface.
2393 @end deftypefun
2395 @comment sys/resource.h
2396 @comment BSD
2397 @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
2398 Store the current value and the maximum value of resource @var{resource}
2399 in @code{*@var{rlp}}.
2401 The return value is @code{0} on success and @code{-1} on failure.  The
2402 following @code{errno} error condition is possible:
2404 @table @code
2405 @item EPERM
2406 You tried to change the maximum permissible limit value,
2407 but you don't have privileges to do so.
2408 @end table
2410 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
2411 32 bits system this function is in fact @code{setrlimit64}.  I.e., the
2412 LFS interface transparently replaces the old interface.
2413 @end deftypefun
2415 @comment sys/resource.h
2416 @comment Unix98
2417 @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
2418 This function is similar to the @code{setrlimit} but its second
2419 parameter is a pointer to a variable of type @code{struct rlimit64}
2420 which allows this function to set values which wouldn't fit in the
2421 member of a @code{struct rlimit}.
2423 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
2424 bits machine this function is available under the name @code{setrlimit}
2425 and so transparently replaces the old interface.
2426 @end deftypefun
2428 @comment sys/resource.h
2429 @comment BSD
2430 @deftp {Data Type} {struct rlimit}
2431 This structure is used with @code{getrlimit} to receive limit values,
2432 and with @code{setrlimit} to specify limit values.  It has two fields:
2434 @table @code
2435 @item rlim_t rlim_cur
2436 The current value of the limit in question.
2437 This is also called the ``soft limit''.
2438 @cindex soft limit
2440 @item rlim_t rlim_max
2441 The maximum permissible value of the limit in question.  You cannot set
2442 the current value of the limit to a larger number than this maximum.
2443 Only the super user can change the maximum permissible value.
2444 This is also called the ``hard limit''.
2445 @cindex hard limit
2446 @end table
2448 In @code{getrlimit}, the structure is an output; it receives the current
2449 values.  In @code{setrlimit}, it specifies the new values.
2450 @end deftp
2452 For the LFS functions a similar type is defined in @file{sys/resource.h}.
2454 @comment sys/resource.h
2455 @comment Unix98
2456 @deftp {Data Type} {struct rlimit64}
2457 This structure is used with @code{getrlimit64} to receive limit values,
2458 and with @code{setrlimit64} to specify limit values.  It has two fields:
2460 @table @code
2461 @item rlim64_t rlim_cur
2462 The current value of the limit in question.
2463 This is also called the ``soft limit''.
2465 @item rlim64_t rlim_max
2466 The maximum permissible value of the limit in question.  You cannot set
2467 the current value of the limit to a larger number than this maximum.
2468 Only the super user can change the maximum permissible value.
2469 This is also called the ``hard limit''.
2470 @end table
2472 In @code{getrlimit64}, the structure is an output; it receives the current
2473 values.  In @code{setrlimit64}, it specifies the new values.
2474 @end deftp
2476 Here is a list of resources that you can specify a limit for.
2477 Those that are sizes are measured in bytes.
2479 @table @code
2480 @comment sys/resource.h
2481 @comment BSD
2482 @item RLIMIT_CPU
2483 @vindex RLIMIT_CPU
2484 The maximum amount of cpu time the process can use.  If it runs for
2485 longer than this, it gets a signal: @code{SIGXCPU}.  The value is
2486 measured in seconds.  @xref{Operation Error Signals}.
2488 @comment sys/resource.h
2489 @comment BSD
2490 @item RLIMIT_FSIZE
2491 @vindex RLIMIT_FSIZE
2492 The maximum size of file the process can create.  Trying to write a
2493 larger file causes a signal: @code{SIGXFSZ}.  @xref{Operation Error
2494 Signals}.
2496 @comment sys/resource.h
2497 @comment BSD
2498 @item RLIMIT_DATA
2499 @vindex RLIMIT_DATA
2500 The maximum size of data memory for the process.  If the process tries
2501 to allocate data memory beyond this amount, the allocation function
2502 fails.
2504 @comment sys/resource.h
2505 @comment BSD
2506 @item RLIMIT_STACK
2507 @vindex RLIMIT_STACK
2508 The maximum stack size for the process.  If the process tries to extend
2509 its stack past this size, it gets a @code{SIGSEGV} signal.
2510 @xref{Program Error Signals}.
2512 @comment sys/resource.h
2513 @comment BSD
2514 @item RLIMIT_CORE
2515 @vindex RLIMIT_CORE
2516 The maximum size core file that this process can create.  If the process
2517 terminates and would dump a core file larger than this maximum size,
2518 then no core file is created.  So setting this limit to zero prevents
2519 core files from ever being created.
2521 @comment sys/resource.h
2522 @comment BSD
2523 @item RLIMIT_RSS
2524 @vindex RLIMIT_RSS
2525 The maximum amount of physical memory that this process should get.
2526 This parameter is a guide for the system's scheduler and memory
2527 allocator; the system may give the process more memory when there is a
2528 surplus.
2530 @comment sys/resource.h
2531 @comment BSD
2532 @item RLIMIT_MEMLOCK
2533 The maximum amount of memory that can be locked into physical memory (so
2534 it will never be paged out).
2536 @comment sys/resource.h
2537 @comment BSD
2538 @item RLIMIT_NPROC
2539 The maximum number of processes that can be created with the same user ID.
2540 If you have reached the limit for your user ID, @code{fork} will fail
2541 with @code{EAGAIN}.  @xref{Creating a Process}.
2543 @comment sys/resource.h
2544 @comment BSD
2545 @item RLIMIT_NOFILE
2546 @vindex RLIMIT_NOFILE
2547 @itemx RLIMIT_OFILE
2548 @vindex RLIMIT_OFILE
2549 The maximum number of files that the process can open.  If it tries to
2550 open more files than this, it gets error code @code{EMFILE}.
2551 @xref{Error Codes}.  Not all systems support this limit; GNU does, and
2552 4.4 BSD does.
2554 @comment sys/resource.h
2555 @comment BSD
2556 @item RLIM_NLIMITS
2557 @vindex RLIM_NLIMITS
2558 The number of different resource limits.  Any valid @var{resource}
2559 operand must be less than @code{RLIM_NLIMITS}.
2560 @end table
2562 @comment sys/resource.h
2563 @comment BSD
2564 @deftypevr Constant int RLIM_INFINITY
2565 This constant stands for a value of ``infinity'' when supplied as
2566 the limit value in @code{setrlimit}.
2567 @end deftypevr
2569 @c ??? Someone want to finish these?
2570 Two historical functions for setting resource limits, @code{ulimit} and
2571 @code{vlimit}, are not documented here.  The latter is declared in
2572 @file{sys/vlimit.h} and comes from BSD.
2574 @node Priority
2575 @section Process Priority
2576 @cindex process priority
2577 @cindex priority of a process
2579 @pindex sys/resource.h
2580 When several processes try to run, their respective priorities determine
2581 what share of the CPU each process gets.  This section describes how you
2582 can read and set the priority of a process.  All these functions and
2583 macros are declared in @file{sys/resource.h}.
2585 The range of valid priority values depends on the operating system, but
2586 typically it runs from @code{-20} to @code{20}.  A lower priority value
2587 means the process runs more often.  These constants describe the range of
2588 priority values:
2590 @table @code
2591 @comment sys/resource.h
2592 @comment BSD
2593 @item PRIO_MIN
2594 @vindex PRIO_MIN
2595 The smallest valid priority value.
2597 @comment sys/resource.h
2598 @comment BSD
2599 @item PRIO_MAX
2600 @vindex PRIO_MAX
2601 The largest valid priority value.
2602 @end table
2604 @comment sys/resource.h
2605 @comment BSD
2606 @deftypefun int getpriority (int @var{class}, int @var{id})
2607 Read the priority of a class of processes; @var{class} and @var{id}
2608 specify which ones (see below).  If the processes specified do not all
2609 have the same priority, this returns the smallest value that any of them
2610 has.
2612 The return value is the priority value on success, and @code{-1} on
2613 failure.  The following @code{errno} error condition are possible for
2614 this function:
2616 @table @code
2617 @item ESRCH
2618 The combination of @var{class} and @var{id} does not match any existing
2619 process.
2621 @item EINVAL
2622 The value of @var{class} is not valid.
2623 @end table
2625 When the return value is @code{-1}, it could indicate failure, or it
2626 could be the priority value.  The only way to make certain is to set
2627 @code{errno = 0} before calling @code{getpriority}, then use @code{errno
2628 != 0} afterward as the criterion for failure.
2629 @end deftypefun
2631 @comment sys/resource.h
2632 @comment BSD
2633 @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{priority})
2634 Set the priority of a class of processes to @var{priority}; @var{class}
2635 and @var{id} specify which ones (see below).
2637 The return value is @code{0} on success and @code{-1} on failure.  The
2638 following @code{errno} error condition are defined for this function:
2640 @table @code
2641 @item ESRCH
2642 The combination of @var{class} and @var{id} does not match any existing
2643 process.
2645 @item EINVAL
2646 The value of @var{class} is not valid.
2648 @item EPERM
2649 You tried to set the priority of some other user's process, and you
2650 don't have privileges for that.
2652 @item EACCES
2653 You tried to lower the priority of a process, and you don't have
2654 privileges for that.
2655 @end table
2656 @end deftypefun
2658 The arguments @var{class} and @var{id} together specify a set of
2659 processes you are interested in.  These are the possible values for
2660 @var{class}:
2662 @table @code
2663 @comment sys/resource.h
2664 @comment BSD
2665 @item PRIO_PROCESS
2666 @vindex PRIO_PROCESS
2667 Read or set the priority of one process.  The argument @var{id} is a
2668 process ID.
2670 @comment sys/resource.h
2671 @comment BSD
2672 @item PRIO_PGRP
2673 @vindex PRIO_PGRP
2674 Read or set the priority of one process group.  The argument @var{id} is
2675 a process group ID.
2677 @comment sys/resource.h
2678 @comment BSD
2679 @item PRIO_USER
2680 @vindex PRIO_USER
2681 Read or set the priority of one user's processes.  The argument @var{id}
2682 is a user ID.
2683 @end table
2685 If the argument @var{id} is 0, it stands for the current process,
2686 current process group, or the current user, according to @var{class}.
2688 @c ??? I don't know where we should say this comes from.
2689 @comment Unix
2690 @comment dunno.h
2691 @deftypefun int nice (int @var{increment})
2692 Increment the priority of the current process by @var{increment}.
2693 The return value is the same as for @code{setpriority}.
2695 Here is an equivalent definition for @code{nice}:
2697 @smallexample
2699 nice (int increment)
2701   int old = getpriority (PRIO_PROCESS, 0);
2702   return setpriority (PRIO_PROCESS, 0, old + increment);
2704 @end smallexample
2705 @end deftypefun