Update.
[glibc.git] / manual / time.texi
blob7b6c4b3a1351e822b7a37e884df8428e18b820b2
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 * Setting an Alarm::            Sending a signal after a specified time.
29 * Sleeping::                    Waiting for a period of time.
30 * Resource Usage::              Measuring various resources used.
31 * Limits on Resources::         Specifying limits on resource usage.
32 * Priority::                    Reading or setting process run priority.
33 @end menu
35 @node Processor Time
36 @section Processor Time
38 If you're trying to optimize your program or measure its efficiency, it's
39 very useful to be able to know how much @dfn{processor time} or @dfn{CPU
40 time} it has used at any given point.  Processor time is different from
41 actual wall clock time because it doesn't include any time spent waiting
42 for I/O or when some other process is running.  Processor time is
43 represented by the data type @code{clock_t}, and is given as a number of
44 @dfn{clock ticks} relative to an arbitrary base time marking the beginning
45 of a single program invocation.
46 @cindex CPU time
47 @cindex processor time
48 @cindex clock ticks
49 @cindex ticks, clock
50 @cindex time, elapsed CPU
52 @menu
53 * Basic CPU Time::              The @code{clock} function.
54 * Detailed CPU Time::           The @code{times} function.
55 @end menu
57 @node Basic CPU Time
58 @subsection Basic CPU Time Inquiry
60 To get the elapsed CPU time used by a process, you can use the
61 @code{clock} function.  This facility is declared in the header file
62 @file{time.h}.
63 @pindex time.h
65 In typical usage, you call the @code{clock} function at the beginning and
66 end of the interval you want to time, subtract the values, and then divide
67 by @code{CLOCKS_PER_SEC} (the number of clock ticks per second), like this:
69 @smallexample
70 @group
71 #include <time.h>
73 clock_t start, end;
74 double elapsed;
76 start = clock();
77 @dots{} /* @r{Do the work.} */
78 end = clock();
79 elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
80 @end group
81 @end smallexample
83 Different computers and operating systems vary wildly in how they keep
84 track of processor time.  It's common for the internal processor clock
85 to have a resolution somewhere between hundredth and millionth of a
86 second.
88 In the GNU system, @code{clock_t} is equivalent to @code{long int} and
89 @code{CLOCKS_PER_SEC} is an integer value.  But in other systems, both
90 @code{clock_t} and the type of the macro @code{CLOCKS_PER_SEC} can be
91 either integer or floating-point types.  Casting processor time values
92 to @code{double}, as in the example above, makes sure that operations
93 such as arithmetic and printing work properly and consistently no matter
94 what the underlying representation is.
96 @comment time.h
97 @comment ISO
98 @deftypevr Macro int CLOCKS_PER_SEC
99 The value of this macro is the number of clock ticks per second measured
100 by the @code{clock} function.
101 @end deftypevr
103 @comment time.h
104 @comment POSIX.1
105 @deftypevr Macro int CLK_TCK
106 This is an obsolete name for @code{CLOCKS_PER_SEC}.
107 @end deftypevr
109 @comment time.h
110 @comment ISO
111 @deftp {Data Type} clock_t
112 This is the type of the value returned by the @code{clock} function.
113 Values of type @code{clock_t} are in units of clock ticks.
114 @end deftp
116 @comment time.h
117 @comment ISO
118 @deftypefun clock_t clock (void)
119 This function returns the elapsed processor time.  The base time is
120 arbitrary but doesn't change within a single process.  If the processor
121 time is not available or cannot be represented, @code{clock} returns the
122 value @code{(clock_t)(-1)}.
123 @end deftypefun
126 @node Detailed CPU Time
127 @subsection Detailed Elapsed CPU Time Inquiry
129 The @code{times} function returns more detailed information about
130 elapsed processor time in a @w{@code{struct tms}} object.  You should
131 include the header file @file{sys/times.h} to use this facility.
132 @pindex sys/times.h
134 @comment sys/times.h
135 @comment POSIX.1
136 @deftp {Data Type} {struct tms}
137 The @code{tms} structure is used to return information about process
138 times.  It contains at least the following members:
140 @table @code
141 @item clock_t tms_utime
142 This is the CPU time used in executing the instructions of the calling
143 process.
145 @item clock_t tms_stime
146 This is the CPU time used by the system on behalf of the calling process.
148 @item clock_t tms_cutime
149 This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
150 values of all terminated child processes of the calling process, whose
151 status has been reported to the parent process by @code{wait} or
152 @code{waitpid}; see @ref{Process Completion}.  In other words, it
153 represents the total CPU time used in executing the instructions of all
154 the terminated child processes of the calling process, excluding child
155 processes which have not yet been reported by @code{wait} or
156 @code{waitpid}.
158 @item clock_t tms_cstime
159 This is similar to @code{tms_cutime}, but represents the total CPU time
160 used by the system on behalf of all the terminated child processes of the
161 calling process.
162 @end table
164 All of the times are given in clock ticks.  These are absolute values; in a
165 newly created process, they are all zero.  @xref{Creating a Process}.
166 @end deftp
168 @comment sys/times.h
169 @comment POSIX.1
170 @deftypefun clock_t times (struct tms *@var{buffer})
171 The @code{times} function stores the processor time information for
172 the calling process in @var{buffer}.
174 The return value is the same as the value of @code{clock()}: the elapsed
175 real time relative to an arbitrary base.  The base is a constant within a
176 particular process, and typically represents the time since system
177 start-up.  A value of @code{(clock_t)(-1)} is returned to indicate failure.
178 @end deftypefun
180 @strong{Portability Note:} The @code{clock} function described in
181 @ref{Basic CPU Time}, is specified by the @w{ISO C} standard.  The
182 @code{times} function is a feature of POSIX.1.  In the GNU system, the
183 value returned by the @code{clock} function is equivalent to the sum of
184 the @code{tms_utime} and @code{tms_stime} fields returned by
185 @code{times}.
187 @node Calendar Time
188 @section Calendar Time
190 This section describes facilities for keeping track of dates and times
191 according to the Gregorian calendar.
192 @cindex Gregorian calendar
193 @cindex time, calendar
194 @cindex date and time
196 There are three representations for date and time information:
198 @itemize @bullet
199 @item
200 @dfn{Calendar time} (the @code{time_t} data type) is a compact
201 representation, typically giving the number of seconds elapsed since
202 some implementation-specific base time.
203 @cindex calendar time
205 @item
206 There is also a @dfn{high-resolution time} representation (the @code{struct
207 timeval} data type) that includes fractions of a second.  Use this time
208 representation instead of ordinary calendar time when you need greater
209 precision.
210 @cindex high-resolution time
212 @item
213 @dfn{Local time} or @dfn{broken-down time} (the @code{struct
214 tm} data type) represents the date and time as a set of components
215 specifying the year, month, and so on, for a specific time zone.
216 This time representation is usually used in conjunction with formatting
217 date and time values.
218 @cindex local time
219 @cindex broken-down time
220 @end itemize
222 @menu
223 * Simple Calendar Time::        Facilities for manipulating calendar time.
224 * High-Resolution Calendar::    A time representation with greater precision.
225 * Broken-down Time::            Facilities for manipulating local time.
226 * Formatting Date and Time::    Converting times to strings.
227 * Parsing Date and Time::       Convert textual time and date information back
228                                  into broken-down time values.
229 * TZ Variable::                 How users specify the time zone.
230 * Time Zone Functions::         Functions to examine or specify the time zone.
231 * Time Functions Example::      An example program showing use of some of
232                                  the time functions.
233 @end menu
235 @node Simple Calendar Time
236 @subsection Simple Calendar Time
238 This section describes the @code{time_t} data type for representing
239 calendar time, and the functions which operate on calendar time objects.
240 These facilities are declared in the header file @file{time.h}.
241 @pindex time.h
243 @cindex epoch
244 @comment time.h
245 @comment ISO
246 @deftp {Data Type} time_t
247 This is the data type used to represent calendar time.
248 When interpreted as an absolute time
249 value, it represents the number of seconds elapsed since 00:00:00 on
250 January 1, 1970, Coordinated Universal Time.  (This date is sometimes
251 referred to as the @dfn{epoch}.)  POSIX requires that this count
252 ignore leap seconds, but on some hosts this count includes leap seconds
253 if you set @code{TZ} to certain values (@pxref{TZ Variable}).
255 In the GNU C library, @code{time_t} is equivalent to @code{long int}.
256 In other systems, @code{time_t} might be either an integer or
257 floating-point type.
258 @end deftp
260 @comment time.h
261 @comment ISO
262 @deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
263 The @code{difftime} function returns the number of seconds elapsed
264 between time @var{time1} and time @var{time0}, as a value of type
265 @code{double}.  The difference ignores leap seconds unless leap
266 second support is enabled.
268 In the GNU system, you can simply subtract @code{time_t} values.  But on
269 other systems, the @code{time_t} data type might use some other encoding
270 where subtraction doesn't work directly.
271 @end deftypefun
273 @comment time.h
274 @comment ISO
275 @deftypefun time_t time (time_t *@var{result})
276 The @code{time} function returns the current time as a value of type
277 @code{time_t}.  If the argument @var{result} is not a null pointer, the
278 time value is also stored in @code{*@var{result}}.  If the calendar
279 time is not available, the value @w{@code{(time_t)(-1)}} is returned.
280 @end deftypefun
283 @node High-Resolution Calendar
284 @subsection High-Resolution Calendar
286 The @code{time_t} data type used to represent calendar times has a
287 resolution of only one second.  Some applications need more precision.
289 So, the GNU C library also contains functions which are capable of
290 representing calendar times to a higher resolution than one second.  The
291 functions and the associated data types described in this section are
292 declared in @file{sys/time.h}.
293 @pindex sys/time.h
295 @comment sys/time.h
296 @comment BSD
297 @deftp {Data Type} {struct timeval}
298 The @code{struct timeval} structure represents a calendar time.  It
299 has the following members:
301 @table @code
302 @item long int tv_sec
303 This represents the number of seconds since the epoch.  It is equivalent
304 to a normal @code{time_t} value.
306 @item long int tv_usec
307 This is the fractional second value, represented as the number of
308 microseconds.
310 Some times struct timeval values are used for time intervals.  Then the
311 @code{tv_sec} member is the number of seconds in the interval, and
312 @code{tv_usec} is the number of additional microseconds.
313 @end table
314 @end deftp
316 @comment sys/time.h
317 @comment BSD
318 @deftp {Data Type} {struct timezone}
319 The @code{struct timezone} structure is used to hold minimal information
320 about the local time zone.  It has the following members:
322 @table @code
323 @item int tz_minuteswest
324 This is the number of minutes west of UTC.
326 @item int tz_dsttime
327 If nonzero, daylight saving time applies during some part of the year.
328 @end table
330 The @code{struct timezone} type is obsolete and should never be used.
331 Instead, use the facilities described in @ref{Time Zone Functions}.
332 @end deftp
334 It is often necessary to subtract two values of type @w{@code{struct
335 timeval}}.  Here is the best way to do this.  It works even on some
336 peculiar operating systems where the @code{tv_sec} member has an
337 unsigned type.
339 @smallexample
340 /* @r{Subtract the `struct timeval' values X and Y,}
341    @r{storing the result in RESULT.}
342    @r{Return 1 if the difference is negative, otherwise 0.}  */
345 timeval_subtract (result, x, y)
346      struct timeval *result, *x, *y;
348   /* @r{Perform the carry for the later subtraction by updating @var{y}.} */
349   if (x->tv_usec < y->tv_usec) @{
350     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
351     y->tv_usec -= 1000000 * nsec;
352     y->tv_sec += nsec;
353   @}
354   if (x->tv_usec - y->tv_usec > 1000000) @{
355     int nsec = (y->tv_usec - x->tv_usec) / 1000000;
356     y->tv_usec += 1000000 * nsec;
357     y->tv_sec -= nsec;
358   @}
360   /* @r{Compute the time remaining to wait.}
361      @r{@code{tv_usec} is certainly positive.} */
362   result->tv_sec = x->tv_sec - y->tv_sec;
363   result->tv_usec = x->tv_usec - y->tv_usec;
365   /* @r{Return 1 if result is negative.} */
366   return x->tv_sec < y->tv_sec;
368 @end smallexample
370 @comment sys/time.h
371 @comment BSD
372 @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
373 The @code{gettimeofday} function returns the current date and time in the
374 @code{struct timeval} structure indicated by @var{tp}.  Information about the
375 time zone is returned in the structure pointed at @var{tzp}.  If the @var{tzp}
376 argument is a null pointer, time zone information is ignored.
378 The return value is @code{0} on success and @code{-1} on failure.  The
379 following @code{errno} error condition is defined for this function:
381 @table @code
382 @item ENOSYS
383 The operating system does not support getting time zone information, and
384 @var{tzp} is not a null pointer.  The GNU operating system does not
385 support using @w{@code{struct timezone}} to represent time zone
386 information; that is an obsolete feature of 4.3 BSD.
387 Instead, use the facilities described in @ref{Time Zone Functions}.
388 @end table
389 @end deftypefun
391 @comment sys/time.h
392 @comment BSD
393 @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
394 The @code{settimeofday} function sets the current date and time
395 according to the arguments.  As for @code{gettimeofday}, time zone
396 information is ignored if @var{tzp} is a null pointer.
398 You must be a privileged user in order to use @code{settimeofday}.
400 The return value is @code{0} on success and @code{-1} on failure.  The
401 following @code{errno} error conditions are defined for this function:
403 @table @code
404 @item EPERM
405 This process cannot set the time because it is not privileged.
407 @item ENOSYS
408 The operating system does not support setting time zone information, and
409 @var{tzp} is not a null pointer.
410 @end table
411 @end deftypefun
413 @comment sys/time.h
414 @comment BSD
415 @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
416 This function speeds up or slows down the system clock in order to make
417 gradual adjustments in the current time.  This ensures that the time
418 reported by the system clock is always monotonically increasing, which
419 might not happen if you simply set the current time.
421 The @var{delta} argument specifies a relative adjustment to be made to
422 the current time.  If negative, the system clock is slowed down for a
423 while until it has lost this much time.  If positive, the system clock
424 is speeded up for a while.
426 If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
427 function returns information about any previous time adjustment that
428 has not yet completed.
430 This function is typically used to synchronize the clocks of computers
431 in a local network.  You must be a privileged user to use it.
432 The return value is @code{0} on success and @code{-1} on failure.  The
433 following @code{errno} error condition is defined for this function:
435 @table @code
436 @item EPERM
437 You do not have privilege to set the time.
438 @end table
439 @end deftypefun
441 @strong{Portability Note:}  The @code{gettimeofday}, @code{settimeofday},
442 and @code{adjtime} functions are derived from BSD.
445 @node Broken-down Time
446 @subsection Broken-down Time
447 @cindex broken-down time
448 @cindex calendar time and broken-down time
450 Calendar time is represented as a number of seconds.  This is convenient
451 for calculation, but has no resemblance to the way people normally
452 represent dates and times.  By contrast, @dfn{broken-down time} is a binary
453 representation separated into year, month, day, and so on.  Broken down
454 time values are not useful for calculations, but they are useful for
455 printing human readable time.
457 A broken-down time value is always relative to a choice of local time
458 zone, and it also indicates which time zone was used.
460 The symbols in this section are declared in the header file @file{time.h}.
462 @comment time.h
463 @comment ISO
464 @deftp {Data Type} {struct tm}
465 This is the data type used to represent a broken-down time.  The structure
466 contains at least the following members, which can appear in any order:
468 @table @code
469 @item int tm_sec
470 This is the number of seconds after the minute, normally in the range
471 @code{0} through @code{59}.  (The actual upper limit is @code{60}, to allow
472 for leap seconds if leap second support is available.)
473 @cindex leap second
475 @item int tm_min
476 This is the number of minutes after the hour, in the range @code{0} through
477 @code{59}.
479 @item int tm_hour
480 This is the number of hours past midnight, in the range @code{0} through
481 @code{23}.
483 @item int tm_mday
484 This is the day of the month, in the range @code{1} through @code{31}.
486 @item int tm_mon
487 This is the number of months since January, in the range @code{0} through
488 @code{11}.
490 @item int tm_year
491 This is the number of years since @code{1900}.
493 @item int tm_wday
494 This is the number of days since Sunday, in the range @code{0} through
495 @code{6}.
497 @item int tm_yday
498 This is the number of days since January 1, in the range @code{0} through
499 @code{365}.
501 @item int tm_isdst
502 @cindex Daylight Saving Time
503 @cindex summer time
504 This is a flag that indicates whether Daylight Saving Time is (or was, or
505 will be) in effect at the time described.  The value is positive if
506 Daylight Saving Time is in effect, zero if it is not, and negative if the
507 information is not available.
509 @item long int tm_gmtoff
510 This field describes the time zone that was used to compute this
511 broken-down time value, including any adjustment for daylight saving; it
512 is the number of seconds that you must add to UTC to get local time.
513 You can also think of this as the number of seconds east of UTC.  For
514 example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
515 The @code{tm_gmtoff} field is derived from BSD and is a GNU library
516 extension; it is not visible in a strict @w{ISO C} environment.
518 @item const char *tm_zone
519 This field is the name for the time zone that was used to compute this
520 broken-down time value.  Like @code{tm_gmtoff}, this field is a BSD and
521 GNU extension, and is not visible in a strict @w{ISO C} environment.
522 @end table
523 @end deftp
525 @comment time.h
526 @comment ISO
527 @deftypefun {struct tm *} localtime (const time_t *@var{time})
528 The @code{localtime} function converts the calendar time pointed to by
529 @var{time} to broken-down time representation, expressed relative to the
530 user's specified time zone.
532 The return value is a pointer to a static broken-down time structure, which
533 might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
534 or @code{localtime}.  (But no other library function overwrites the contents
535 of this object.)
537 The return value is the null pointer if @var{time} cannot be represented
538 as a broken-down time; typically this is because the year cannot fit into
539 an @code{int}.
541 Calling @code{localtime} has one other effect: it sets the variable
542 @code{tzname} with information about the current time zone.  @xref{Time
543 Zone Functions}.
544 @end deftypefun
546 Using the @code{localtime} function is a big problem in multi-threaded
547 programs.  The result is returned in a static buffer and this is used in
548 all threads.  POSIX.1c introduced a varient of this function.
550 @comment time.h
551 @comment POSIX.1c
552 @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
553 The @code{localtime_r} function works just like the @code{localtime}
554 function.  It takes a pointer to a variable containing the calendar time
555 and converts it to the broken-down time format.
557 But the result is not placed in a static buffer.  Instead it is placed
558 in the object of type @code{struct tm} to which the parameter
559 @var{resultp} points.
561 If the conversion is successful the function returns a pointer to the
562 object the result was written into, i.e., it returns @var{resultp}.
563 @end deftypefun
566 @comment time.h
567 @comment ISO
568 @deftypefun {struct tm *} gmtime (const time_t *@var{time})
569 This function is similar to @code{localtime}, except that the broken-down
570 time is expressed as Coordinated Universal Time (UTC)---that is, as
571 Greenwich Mean Time (GMT)---rather than relative to the local time zone.
573 Recall that calendar times are @emph{always} expressed in coordinated
574 universal time.
575 @end deftypefun
577 As for the @code{localtime} function we have the problem that the result
578 is placed in a static variable.  POSIX.1c also provides a replacement for
579 @code{gmtime}.
581 @comment time.h
582 @comment POSIX.1c
583 @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
584 This function is similar to @code{localtime_r}, except that it converts
585 just like @code{gmtime} the given time as Coordinated Universal Time.
587 If the conversion is successful the function returns a pointer to the
588 object the result was written into, i.e., it returns @var{resultp}.
589 @end deftypefun
592 @comment time.h
593 @comment ISO
594 @deftypefun time_t mktime (struct tm *@var{brokentime})
595 The @code{mktime} function is used to convert a broken-down time structure
596 to a calendar time representation.  It also ``normalizes'' the contents of
597 the broken-down time structure, by filling in the day of week and day of
598 year based on the other date and time components.
600 The @code{mktime} function ignores the specified contents of the
601 @code{tm_wday} and @code{tm_yday} members of the broken-down time
602 structure.  It uses the values of the other components to compute the
603 calendar time; it's permissible for these components to have
604 unnormalized values outside of their normal ranges.  The last thing that
605 @code{mktime} does is adjust the components of the @var{brokentime}
606 structure (including the @code{tm_wday} and @code{tm_yday}).
608 If the specified broken-down time cannot be represented as a calendar time,
609 @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
610 the contents of @var{brokentime}.
612 Calling @code{mktime} also sets the variable @code{tzname} with
613 information about the current time zone.  @xref{Time Zone Functions}.
614 @end deftypefun
616 @node Formatting Date and Time
617 @subsection Formatting Date and Time
619 The functions described in this section format time values as strings.
620 These functions are declared in the header file @file{time.h}.
621 @pindex time.h
623 @comment time.h
624 @comment ISO
625 @deftypefun {char *} asctime (const struct tm *@var{brokentime})
626 The @code{asctime} function converts the broken-down time value that
627 @var{brokentime} points to into a string in a standard format:
629 @smallexample
630 "Tue May 21 13:46:22 1991\n"
631 @end smallexample
633 The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
634 @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
636 The abbreviations for the months are: @samp{Jan}, @samp{Feb},
637 @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
638 @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
640 The return value points to a statically allocated string, which might be
641 overwritten by subsequent calls to @code{asctime} or @code{ctime}.
642 (But no other library function overwrites the contents of this
643 string.)
644 @end deftypefun
646 @comment time.h
647 @comment POSIX.1c
648 @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
649 This function is similar to @code{asctime} but instead of placing the
650 result in a static buffer it writes the string in the buffer pointed to
651 by the parameter @var{buffer}.  This buffer should have at least room
652 for 16 bytes.
654 If no error occurred the function returns a pointer to the string the
655 result was written into, i.e., it returns @var{buffer}.  Otherwise
656 return @code{NULL}.
657 @end deftypefun
660 @comment time.h
661 @comment ISO
662 @deftypefun {char *} ctime (const time_t *@var{time})
663 The @code{ctime} function is similar to @code{asctime}, except that the
664 time value is specified as a @code{time_t} calendar time value rather
665 than in broken-down local time format.  It is equivalent to
667 @smallexample
668 asctime (localtime (@var{time}))
669 @end smallexample
671 @code{ctime} sets the variable @code{tzname}, because @code{localtime}
672 does so.  @xref{Time Zone Functions}.
673 @end deftypefun
675 @comment time.h
676 @comment POSIX.1c
677 @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
678 This function is similar to @code{ctime}, only that it places the result
679 in the string pointed to by @var{buffer}.  It is equivalent to (written
680 using gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
682 @smallexample
683 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
684 @end smallexample
686 If no error occurred the function returns a pointer to the string the
687 result was written into, i.e., it returns @var{buffer}.  Otherwise
688 return @code{NULL}.
689 @end deftypefun
692 @comment time.h
693 @comment ISO
694 @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
695 This function is similar to the @code{sprintf} function (@pxref{Formatted
696 Input}), but the conversion specifications that can appear in the format
697 template @var{template} are specialized for printing components of the date
698 and time @var{brokentime} according to the locale currently specified for
699 time conversion (@pxref{Locales}).
701 Ordinary characters appearing in the @var{template} are copied to the
702 output string @var{s}; this can include multibyte character sequences.
703 Conversion specifiers are introduced by a @samp{%} character, followed
704 by an optional flag which can be one of the following.  These flags
705 are all GNU extensions. The first three affect only the output of
706 numbers:
708 @table @code
709 @item _
710 The number is padded with spaces.
712 @item -
713 The number is not padded at all.
715 @item 0
716 The number is padded with zeros even if the format specifies padding
717 with spaces.
719 @item ^
720 The output uses uppercase characters, but only if this is possible
721 (@pxref{Case Conversion}).
722 @end table
724 The default action is to pad the number with zeros to keep it a constant
725 width.  Numbers that do not have a range indicated below are never
726 padded, since there is no natural width for them.
728 Following the flag an optional specification of the width is possible.
729 This is specified in decimal notation.  If the natural size of the
730 output is of the field has less than the specified number of characters,
731 the result is written right adjusted and space padded to the given
732 size.
734 An optional modifier can follow the optional flag and width
735 specification.  The modifiers, which are POSIX.2 extensions, are:
737 @table @code
738 @item E
739 Use the locale's alternate representation for date and time.  This
740 modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
741 @code{%y} and @code{%Y} format specifiers.  In a Japanese locale, for
742 example, @code{%Ex} might yield a date format based on the Japanese
743 Emperors' reigns.
745 @item O
746 Use the locale's alternate numeric symbols for numbers.  This modifier
747 applies only to numeric format specifiers.
748 @end table
750 If the format supports the modifier but no alternate representation
751 is available, it is ignored.
753 The conversion specifier ends with a format specifier taken from the
754 following list.  The whole @samp{%} sequence is replaced in the output
755 string as follows:
757 @table @code
758 @item %a
759 The abbreviated weekday name according to the current locale.
761 @item %A
762 The full weekday name according to the current locale.
764 @item %b
765 The abbreviated month name according to the current locale.
767 @item %B
768 The full month name according to the current locale.
770 @item %c
771 The preferred date and time representation for the current locale.
773 @item %C
774 The century of the year.  This is equivalent to the greatest integer not
775 greater than the year divided by 100.
777 This format is a POSIX.2 extension.
779 @item %d
780 The day of the month as a decimal number (range @code{01} through @code{31}).
782 @item %D
783 The date using the format @code{%m/%d/%y}.
785 This format is a POSIX.2 extension.
787 @item %e
788 The day of the month like with @code{%d}, but padded with blank (range
789 @code{ 1} through @code{31}).
791 This format is a POSIX.2 extension.
793 @item %F
794 The date using the format @code{%Y-%m-%d}.  This is the form specified
795 in the @w{ISO 8601} standard and is the preferred form for all uses.
797 This format is a @w{ISO C 9X} extension.
799 @item %g
800 The year corresponding to the ISO week number, but without the century
801 (range @code{00} through @code{99}).  This has the same format and value
802 as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
803 to the previous or next year, that year is used instead.
805 This format is a GNU extension.
807 @item %G
808 The year corresponding to the ISO week number.  This has the same format
809 and value as @code{%Y}, except that if the ISO week number (see
810 @code{%V}) belongs to the previous or next year, that year is used
811 instead.
813 This format is a GNU extension.
815 @item %h
816 The abbreviated month name according to the current locale.  The action
817 is the same as for @code{%b}.
819 This format is a POSIX.2 extension.
821 @item %H
822 The hour as a decimal number, using a 24-hour clock (range @code{00} through
823 @code{23}).
825 @item %I
826 The hour as a decimal number, using a 12-hour clock (range @code{01} through
827 @code{12}).
829 @item %j
830 The day of the year as a decimal number (range @code{001} through @code{366}).
832 @item %k
833 The hour as a decimal number, using a 24-hour clock like @code{%H}, but
834 padded with blank (range @code{ 0} through @code{23}).
836 This format is a GNU extension.
838 @item %l
839 The hour as a decimal number, using a 12-hour clock like @code{%I}, but
840 padded with blank (range @code{ 1} through @code{12}).
842 This format is a GNU extension.
844 @item %m
845 The month as a decimal number (range @code{01} through @code{12}).
847 @item %M
848 The minute as a decimal number (range @code{00} through @code{59}).
850 @item %n
851 A single @samp{\n} (newline) character.
853 This format is a POSIX.2 extension.
855 @item %p
856 Either @samp{AM} or @samp{PM}, according to the given time value; or the
857 corresponding strings for the current locale.  Noon is treated as
858 @samp{PM} and midnight as @samp{AM}.
860 @ignore
861 We currently have a problem with makeinfo.  Write @samp{AM} and @samp{am}
862 both results in `am'.  I.e., the difference in case is not visible anymore.
863 @end ignore
864 @item %P
865 Either @samp{am} or @samp{pm}, according to the given time value; or the
866 corresponding strings for the current locale, printed in lowercase
867 characters.  Noon is treated as @samp{pm} and midnight as @samp{am}.
869 This format is a GNU extension.
871 @item %r
872 The complete time using the AM/PM format of the current locale.
874 This format is a POSIX.2 extension.
876 @item %R
877 The hour and minute in decimal numbers using the format @code{%H:%M}.
879 This format is a GNU extension.
881 @item %s
882 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
883 Leap seconds are not counted unless leap second support is available.
885 This format is a GNU extension.
887 @item %S
888 The seconds as a decimal number (range @code{00} through @code{60}).
890 @item %t
891 A single @samp{\t} (tabulator) character.
893 This format is a POSIX.2 extension.
895 @item %T
896 The time using decimal numbers using the format @code{%H:%M:%S}.
898 This format is a POSIX.2 extension.
900 @item %u
901 The day of the week as a decimal number (range @code{1} through
902 @code{7}), Monday being @code{1}.
904 This format is a POSIX.2 extension.
906 @item %U
907 The week number of the current year as a decimal number (range @code{00}
908 through @code{53}), starting with the first Sunday as the first day of
909 the first week.  Days preceding the first Sunday in the year are
910 considered to be in week @code{00}.
912 @item %V
913 The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
914 through @code{53}).  ISO weeks start with Monday and end with Sunday.
915 Week @code{01} of a year is the first week which has the majority of its
916 days in that year; this is equivalent to the week containing the year's
917 first Thursday, and it is also equivalent to the week containing January
918 4.  Week @code{01} of a year can contain days from the previous year.
919 The week before week @code{01} of a year is the last week (@code{52} or
920 @code{53}) of the previous year even if it contains days from the new
921 year.
923 This format is a POSIX.2 extension.
925 @item %w
926 The day of the week as a decimal number (range @code{0} through
927 @code{6}), Sunday being @code{0}.
929 @item %W
930 The week number of the current year as a decimal number (range @code{00}
931 through @code{53}), starting with the first Monday as the first day of
932 the first week.  All days preceding the first Monday in the year are
933 considered to be in week @code{00}.
935 @item %x
936 The preferred date representation for the current locale, but without the
937 time.
939 @item %X
940 The preferred time representation for the current locale, but with no date.
942 @item %y
943 The year without a century as a decimal number (range @code{00} through
944 @code{99}).  This is equivalent to the year modulo 100.
946 @item %Y
947 The year as a decimal number, using the Gregorian calendar.  Years
948 before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
950 @item %z
951 @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
952 @code{-0600} or @code{+0100}), or nothing if no time zone is
953 determinable.
955 This format is a GNU extension.
957 A full @w{RFC 822} timestamp is generated by the format
958 @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
959 @w{@samp{"%a, %d %b %Y %T %z"}}).
961 @item %Z
962 The time zone abbreviation (empty if the time zone can't be determined).
964 @item %%
965 A literal @samp{%} character.
966 @end table
968 The @var{size} parameter can be used to specify the maximum number of
969 characters to be stored in the array @var{s}, including the terminating
970 null character.  If the formatted time requires more than @var{size}
971 characters, @code{strftime} returns zero and the content of the array
972 @var{s} is indetermined.  Otherwise the return value indicates the
973 number of characters placed in the array @var{s}, not including the
974 terminating null character.
976 @emph{Warning:} This convention for the return value which is prescribed
977 in @w{ISO C} can lead to problems in some situations.  For certain
978 format strings and certain locales the output really can be the empty
979 string and this cannot be discovered by testing the return value only.
980 E.g., in most locales the AM/PM time format is not supported (most of
981 the world uses the 24 hour time representation).  In such locales
982 @code{"%p"} will return the empty string, i.e., the return value is
983 zero.  To detect situations like this something similar to the following
984 code should be used:
986 @smallexample
987 buf[0] = '\1';
988 len = strftime (buf, bufsize, format, tp);
989 if (len == 0 && buf[0] != '\0')
990   @{
991     /* Something went wrong in the strftime call.  */
992     @dots{}
993   @}
994 @end smallexample
996 If @var{s} is a null pointer, @code{strftime} does not actually write
997 anything, but instead returns the number of characters it would have written.
999 According to POSIX.1 every call to @code{strftime} implies a call to
1000 @code{tzset}.  So the contents of the environment variable @code{TZ}
1001 is examined before any output is produced.
1003 For an example of @code{strftime}, see @ref{Time Functions Example}.
1004 @end deftypefun
1006 @node Parsing Date and Time
1007 @subsection Convert textual time and date information back
1009 The @w{ISO C} standard does not specify any functions which can convert
1010 the output of the @code{strftime} function back into a binary format.
1011 This lead to variety of more or less successful implementations with
1012 different interfaces over the years.  Then the Unix standard got
1013 extended by two functions: @code{strptime} and @code{getdate}.  Both
1014 have kind of strange interfaces but at least they are widely available.
1016 @menu
1017 * Low-Level Time String Parsing::  Interpret string according to given format.
1018 * General Time String Parsing::    User-friendly function to parse data and
1019                                     time strings.
1020 @end menu
1022 @node Low-Level Time String Parsing
1023 @subsubsection Interpret string according to given format
1025 The first function is a rather low-level interface.  It is nevertheless
1026 frequently used in user programs since it is better known.  Its
1027 implementation and the interface though is heavily influenced by the
1028 @code{getdate} function which is defined and implemented in terms of
1029 calls to @code{strptime}.
1031 @comment time.h
1032 @comment XPG4
1033 @deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1034 The @code{strptime} function parses the input string @var{s} according
1035 to the format string @var{fmt} and stores the found values in the
1036 structure @var{tp}.
1038 The input string can be retrieved in any way.  It does not matter
1039 whether it was generated by a @code{strftime} call or made up directly
1040 by a program.  It is also not necessary that the content is in any
1041 human-recognizable format.  I.e., it is OK if a date is written like
1042 @code{"02:1999:9"} which is not understandable without context.  As long
1043 the format string @var{fmt} matches the format of the input string
1044 everything goes.
1046 The format string consists of the same components as the format string
1047 for the @code{strftime} function.  The only difference is that the flags
1048 @code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1049 @comment Is this really the intention?  --drepper
1050 Several of the formats which @code{strftime} handled differently do the
1051 same work in @code{strptime} since differences like case of the output
1052 do not matter.  For symmetry reasons all formats are supported, though.
1054 The modifiers @code{E} and @code{O} are also allowed everywhere the
1055 @code{strftime} function allows them.
1057 The formats are:
1059 @table @code
1060 @item %a
1061 @itemx %A
1062 The weekday name according to the current locale, in abbreviated form or
1063 the full name.
1065 @item %b
1066 @itemx %B
1067 @itemx %h
1068 The month name according to the current locale, in abbreviated form or
1069 the full name.
1071 @item %c
1072 The date and time representation for the current locale.
1074 @item %Ec
1075 Like @code{%c} but the locale's alternative date and time format is used.
1077 @item %C
1078 The century of the year.
1080 It makes sense to use this format only if the format string also
1081 contains the @code{%y} format.
1083 @item %EC
1084 The locale's representation of the period.
1086 Unlike @code{%C} it makes sometimes sense to use this format since in
1087 some cultures it is required to specify years relative to periods
1088 instead of using the Gregorian years.
1090 @item %d
1091 @item %e
1092 The day of the month as a decimal number (range @code{1} through @code{31}).
1093 Leading zeroes are permitted but not required.
1095 @item %Od
1096 @itemx %Oe
1097 Same as @code{%d} but the locale's alternative numeric symbols are used.
1099 Leading zeroes are permitted but not required.
1101 @item %D
1102 Equivalent to the use of @code{%m/%d/%y} in this place.
1104 @item %F
1105 Equivalent to the use of @code{%Y-%m-%d} which is the @w{ISO 8601} date
1106 format.
1108 This is a GNU extension following an @w{ISO C 9X} extension to
1109 @code{strftime}.
1111 @item %g
1112 The year corresponding to the ISO week number, but without the century
1113 (range @code{00} through @code{99}).
1115 @emph{Note:} This is not really implemented currently.  The format is
1116 recognized, input is consumed but no field in @var{tm} is set.
1118 This format is a GNU extension following a GNU extension of @code{strftime}.
1120 @item %G
1121 The year corresponding to the ISO week number.
1123 @emph{Note:} This is not really implemented currently.  The format is
1124 recognized, input is consumed but no field in @var{tm} is set.
1126 This format is a GNU extension following a GNU extension of @code{strftime}.
1128 @item %H
1129 @itemx %k
1130 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1131 @code{23}).
1133 @code{%k} is a GNU extension following a GNU extension of @code{strftime}.
1135 @item %OH
1136 Same as @code{%H} but using the locale's alternative numeric symbols are used.
1138 @item %I
1139 @itemx %l
1140 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1141 @code{12}).
1143 @code{%l} is a GNU extension following a GNU extension of @code{strftime}.
1145 @item %OI
1146 Same as @code{%I} but using the locale's alternative numeric symbols are used.
1148 @item %j
1149 The day of the year as a decimal number (range @code{1} through @code{366}).
1151 Leading zeroes are permitted but not required.
1153 @item %m
1154 The month as a decimal number (range @code{1} through @code{12}).
1156 Leading zeroes are permitted but not required.
1158 @item %Om
1159 Same as @code{%m} but using the locale's alternative numeric symbols are used.
1161 @item %M
1162 The minute as a decimal number (range @code{0} through @code{59}).
1164 Leading zeroes are permitted but not required.
1166 @item %OM
1167 Same as @code{%M} but using the locale's alternative numeric symbols are used.
1169 @item %n
1170 @itemx %t
1171 Matches any white space.
1173 @item %p
1174 @item %P
1175 The locale-dependent equivalent to @samp{AM} or @samp{PM}.
1177 This format is not useful unless @code{%I} or @code{%l} is also used.
1178 Another complication is that the locale might not define these values at
1179 all and therefore the conversion fails.
1181 @code{%P} is a GNU extension following a GNU extension to @code{strftime}.
1183 @item %r
1184 The complete time using the AM/PM format of the current locale.
1186 A complication is that the locale might not define this format at all
1187 and therefore the conversion fails.
1189 @item %R
1190 The hour and minute in decimal numbers using the format @code{%H:%M}.
1192 @code{%R} is a GNU extension following a GNU extension to @code{strftime}.
1194 @item %s
1195 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1196 Leap seconds are not counted unless leap second support is available.
1198 @code{%s} is a GNU extension following a GNU extension to @code{strftime}.
1200 @item %S
1201 The seconds as a decimal number (range @code{0} through @code{61}).
1203 Leading zeroes are permitted but not required.
1205 Please note the nonsense with @code{61} being allowed.  This is what the
1206 Unix specification says.  They followed the stupid decision once made to
1207 allow double leap seconds.  These do not exist but the myth persists.
1209 @item %OS
1210 Same as @code{%S} but using the locale's alternative numeric symbols are used.
1212 @item %T
1213 Equivalent to the use of @code{%H:%M:%S} in this place.
1215 @item %u
1216 The day of the week as a decimal number (range @code{1} through
1217 @code{7}), Monday being @code{1}.
1219 Leading zeroes are permitted but not required.
1221 @emph{Note:} This is not really implemented currently.  The format is
1222 recognized, input is consumed but no field in @var{tm} is set.
1224 @item %U
1225 The week number of the current year as a decimal number (range @code{0}
1226 through @code{53}).
1228 Leading zeroes are permitted but not required.
1230 @item %OU
1231 Same as @code{%U} but using the locale's alternative numeric symbols are used.
1233 @item %V
1234 The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
1235 through @code{53}).
1237 Leading zeroes are permitted but not required.
1239 @emph{Note:} This is not really implemented currently.  The format is
1240 recognized, input is consumed but no field in @var{tm} is set.
1242 @item %w
1243 The day of the week as a decimal number (range @code{0} through
1244 @code{6}), Sunday being @code{0}.
1246 Leading zeroes are permitted but not required.
1248 @emph{Note:} This is not really implemented currently.  The format is
1249 recognized, input is consumed but no field in @var{tm} is set.
1251 @item %Ow
1252 Same as @code{%w} but using the locale's alternative numeric symbols are used.
1254 @item %W
1255 The week number of the current year as a decimal number (range @code{0}
1256 through @code{53}).
1258 Leading zeroes are permitted but not required.
1260 @emph{Note:} This is not really implemented currently.  The format is
1261 recognized, input is consumed but no field in @var{tm} is set.
1263 @item %OW
1264 Same as @code{%W} but using the locale's alternative numeric symbols are used.
1266 @item %x
1267 The date using the locale's date format.
1269 @item %Ex
1270 Like @code{%x} but the locale's alternative data representation is used.
1272 @item %X
1273 The time using the locale's time format.
1275 @item %EX
1276 Like @code{%X} but the locale's alternative time representation is used.
1278 @item %y
1279 The year without a century as a decimal number (range @code{0} through
1280 @code{99}).
1282 Leading zeroes are permitted but not required.
1284 Please note that it is at least questionable to use this format without
1285 the @code{%C} format.  The @code{strptime} function does regard input
1286 values in the range @math{68} to @math{99} as the years @math{1969} to
1287 @math{1999} and the values @math{0} to @math{68} as the years
1288 @math{2000} to @math{2068}.  But maybe this heuristic fails for some
1289 input data.
1291 Therefore it is best to avoid @code{%y} completely and use @code{%Y}
1292 instead.
1294 @item %Ey
1295 The offset from @code{%EC} in the locale's alternative representation.
1297 @item %Oy
1298 The offset of the year (from @code{%C}) using the locale's alternative
1299 numeric symbols.
1301 @item %Y
1302 The year as a decimal number, using the Gregorian calendar.
1304 @item %EY
1305 The full alternative year representation.
1307 @item %z
1308 Equivalent to the use of @code{%a, %d %b %Y %H:%M:%S %z} in this place.
1309 This is the full @w{ISO 8601} date and time format.
1311 @item %Z
1312 The timezone name.
1314 @emph{Note:} This is not really implemented currently.  The format is
1315 recognized, input is consumed but no field in @var{tm} is set.
1317 @item %%
1318 A literal @samp{%} character.
1319 @end table
1321 All other characters in the format string must have a matching character
1322 in the input string.  Exceptions are white spaces in the input string
1323 which can match zero or more white space characters in the input string.
1325 The @code{strptime} function processes the input string from right to
1326 left.  Each of the three possible input elements (white space, literal,
1327 or format) are handled one after the other.  If the input cannot be
1328 matched to the format string the function stops.  The remainder of the
1329 format and input strings are not processed.
1331 The return value of the function is a pointer to the first character not
1332 processed in this function call.  In the case of an error the return
1333 value points to the first character not matched.  In case the input
1334 string contains more than required by the format string the return value
1335 points right after the last consumed input character.  In case the whole
1336 input string is consumed the return value points to the NUL byte at the
1337 end of the string.
1338 @end deftypefun
1340 The specification of the function in the XPG standard is rather vague.
1341 It leaves out a few important pieces of information.  Most important it
1342 does not specify what happens to those elements of @var{tm} which are
1343 not directly initialized by the different formats.  Various
1344 implementations on different Unix systems vary here.
1346 The GNU libc implementation does not touch those fields which are not
1347 directly initialized.  Exceptions are the @code{tm_wday} and
1348 @code{tm_yday} elements which are recomputed if any of the year, month,
1349 or date elements changed.  This has two implications:
1351 @itemize @bullet
1352 @item
1353 Before calling the @code{strptime} function for a new input string one
1354 has to prepare the structure passed in as the @var{tm}.  Normally this
1355 will mean that all values are initialized to zero.  Alternatively one
1356 can use all fields to values like @code{INT_MAX} which allows to
1357 determine which elements were set by the function call.  Zero does not
1358 work here since it is a valid value for many of the fields.
1360 Careful initialization is necessary if one wants to find out whether a
1361 certain field in @var{tm} was initialized by the function call.
1363 @item
1364 One can construct a @code{struct tm} value in several @code{strptime}
1365 calls in a row.  A useful application of this is for example the parsing
1366 of two separate strings, one containing the date information, the other
1367 the time information.  By parsing both one after the other without
1368 clearing the structure in between one can construct a complete
1369 broken-down time.
1370 @end itemize
1372 The following example shows a function which parses a string which is
1373 supposed to contain the date information in either US style or @w{ISO
1374 8601} form.
1376 @smallexample
1377 const char *
1378 parse_date (const char *input, struct tm *tm)
1380   const char *cp;
1382   /* @r{First clear the result structure.}  */
1383   memset (tm, '\0', sizeof (*tm));
1385   /* @r{Try the ISO format first.}  */
1386   cp = strptime (input, "%F", tm);
1387   if (cp == NULL)
1388     @{
1389       /* @r{Does not match.  Try the US form.}  */
1390       cp = strptime (input, "%D", tm);
1391     @}
1393   return cp;
1395 @end smallexample
1397 @node General Time String Parsing
1398 @subsubsection A user-friendlier way to parse times and dates
1400 The Unix standard defines another function to parse date strings.  The
1401 interface is, mildly said, weird.  But if this function fits into the
1402 application to be written it is just fine.  It is a problem when using
1403 this function in multi-threaded programs or in libraries since it
1404 returns a pointer to a static variable, uses a global variable, and a
1405 global state (an environment variable).
1407 @comment time.h
1408 @comment Unix98
1409 @defvar getdate_err
1410 This variable of type @code{int} will contain the error code of the last
1411 unsuccessful call of the @code{getdate} function.  Defined values are:
1413 @table @math
1414 @item 1
1415 The environment variable @code{DATEMSK} is not defined or null.
1416 @item 2
1417 The template file denoted by the @code{DATEMSK} environment variable
1418 cannot be opened.
1419 @item 3
1420 Information about the template file cannot retrieved.
1421 @item 4
1422 The template file is no regular file.
1423 @item 5
1424 An I/O error occurred while reading the template file.
1425 @item 6
1426 Not enough memory available to execute the function.
1427 @item 7
1428 The template file contains no matching template.
1429 @item 8
1430 The input string is invalid for a template which would match otherwise.
1431 This includes error like February 31st, or return values which can be
1432 represented using @code{time_t}.
1433 @end table
1434 @end defvar
1436 @comment time.h
1437 @comment Unix98
1438 @deftypefun {struct tm *} getdate (const char *@var{string})
1439 The interface of the @code{getdate} function is the simplest possible
1440 for a function to parse a string and return the value.  @var{string} is
1441 the input string and the result is passed to the user in a statically
1442 allocated variable.
1444 The details about how the string is processed is hidden from the user.
1445 In fact, it can be outside the control of the program.  Which formats
1446 are recognized is controlled by the file named by the environment
1447 variable @code{DATEMSK}.  The content of the named file should contain
1448 lines of valid format strings which could be passed to @code{strptime}.
1450 The @code{getdate} function reads these format strings one after the
1451 other and tries to match the input string.  The first line which
1452 completely matches the input string is used.
1454 Elements which were not initialized through the format string get
1455 assigned the values of the time the @code{getdate} function is called.
1457 The format elements recognized by @code{getdate} are the same as for
1458 @code{strptime}.  See above for an explanation.  There are only a few
1459 extension to the @code{strptime} behavior:
1461 @itemize @bullet
1462 @item
1463 If the @code{%Z} format is given the broken-down time is based on the
1464 current time in the timezone matched, not in the current timezone of the
1465 runtime environment.
1467 @emph{Note}: This is not implemented (currently).  The problem is that
1468 timezone names are not unique.  If a fixed timezone is assumed for a
1469 given string (say @code{EST} meaning US East Coast time) uses for
1470 countries other than the USA will fail.  So far we have found no good
1471 solution for this.
1473 @item
1474 If only the weekday is specified the selected day depends on the current
1475 date.  If the current weekday is greater or equal to the @code{tm_wday}
1476 value this weeks day is selected.  Otherwise next weeks day.
1478 @item
1479 A similar heuristic is used if only the month is given, not the year.
1480 For value corresponding to the current or a later month the current year
1481 s used.  Otherwise the next year.  The first day of the month is assumed
1482 if it is not explicitly specified.
1484 @item
1485 The current hour, minute, and second is used if the appropriate value is
1486 not set through the format.
1488 @item
1489 If no date is given the date for the next day is used if the time is
1490 smaller than the current time.  Otherwise it is the same day.
1491 @end itemize
1493 It should be noted that the format in the template file need not only
1494 contain format elements.  The following is a list of possible format
1495 strings (taken from the Unix standard):
1497 @smallexample
1499 %A %B %d, %Y %H:%M:%S
1502 %m/%d/%y %I %p
1503 %d,%m,%Y %H:%M
1504 at %A the %dst of %B in %Y
1505 run job at %I %p,%B %dnd
1506 %A den %d. %B %Y %H.%M Uhr
1507 @end smallexample
1509 As one can see the template list can contain very specific strings like
1510 @code{run job at %I %p,%B %dnd}.  Using the above list of templates and
1511 assuming the current time is Mon Sep 22 12:19:47 EDT 1986 we can get the
1512 The results for the given input.
1514 @multitable {xxxxxxxxxxxx} {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1515 @item        Mon @tab       %a @tab    Mon Sep 22 12:19:47 EDT 1986
1516 @item        Sun @tab       %a @tab    Sun Sep 28 12:19:47 EDT 1986
1517 @item        Fri @tab       %a @tab    Fri Sep 26 12:19:47 EDT 1986
1518 @item        September @tab %B @tab    Mon Sep 1 12:19:47 EDT 1986
1519 @item        January @tab   %B @tab    Thu Jan 1 12:19:47 EST 1987
1520 @item        December @tab  %B @tab    Mon Dec 1 12:19:47 EST 1986
1521 @item        Sep Mon @tab   %b %a @tab Mon Sep 1 12:19:47 EDT 1986
1522 @item        Jan Fri @tab   %b %a @tab Fri Jan 2 12:19:47 EST 1987
1523 @item        Dec Mon @tab   %b %a @tab Mon Dec 1 12:19:47 EST 1986
1524 @item        Jan Wed 1989 @tab  %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
1525 @item        Fri 9 @tab     %a %H @tab Fri Sep 26 09:00:00 EDT 1986
1526 @item        Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
1527 @item        10:30 @tab     %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
1528 @item        13:30 @tab     %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
1529 @end multitable
1531 The return value of the function is a pointer to a static variable of
1532 type @w{@code{struct tm}} or a null pointer if an error occurred.  The
1533 result in the variable pointed to by the return value is only valid
1534 until the next @code{getdate} call which makes this function unusable in
1535 multi-threaded applications.
1537 The @code{errno} variable is @emph{not} changed.  Error conditions are
1538 signalled using the global variable @code{getdate_err}.  See the
1539 description above for a list of the possible error values.
1541 @emph{Warning:} The @code{getdate} function should @emph{never} be
1542 used in SUID-programs.  The reason is obvious: using the
1543 @code{DATEMSK} environment variable one can get the function to open
1544 any arbitrary file and changes are high that with some bogus input
1545 (such as a binary file) the program will crash.
1546 @end deftypefun
1548 @comment time.h
1549 @comment GNU
1550 @deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
1551 The @code{getdate_r} function is the reentrant counterpart of
1552 @code{getdate}.  It does not use the global variable @code{getdate_err}
1553 to signal the error but instead the return value now is this error code.
1554 The same error codes as described in the @code{getdate_err}
1555 documentation above are used.
1557 @code{getdate_r} also does not store the broken-down time in a static
1558 variable.  Instead it takes an second argument which must be a pointer
1559 to a variable of type @code{struct tm} where the broken-down can be
1560 stored.
1562 This function is not defined in the Unix standard.  Nevertheless it is
1563 available on some other Unix systems as well.
1565 As for @code{getdate} the warning for using this function in
1566 SUID-programs applies to @code{getdate_r} as well.
1567 @end deftypefun
1569 @node TZ Variable
1570 @subsection Specifying the Time Zone with @code{TZ}
1572 In POSIX systems, a user can specify the time zone by means of the
1573 @code{TZ} environment variable.  For information about how to set
1574 environment variables, see @ref{Environment Variables}.  The functions
1575 for accessing the time zone are declared in @file{time.h}.
1576 @pindex time.h
1577 @cindex time zone
1579 You should not normally need to set @code{TZ}.  If the system is
1580 configured properly, the default time zone will be correct.  You might
1581 set @code{TZ} if you are using a computer over the network from a
1582 different time zone, and would like times reported to you in the time zone
1583 that local for you, rather than what is local for the computer.
1585 In POSIX.1 systems the value of the @code{TZ} variable can be of one of
1586 three formats.  With the GNU C library, the most common format is the
1587 last one, which can specify a selection from a large database of time
1588 zone information for many regions of the world.  The first two formats
1589 are used to describe the time zone information directly, which is both
1590 more cumbersome and less precise.  But the POSIX.1 standard only
1591 specifies the details of the first two formats, so it is good to be
1592 familiar with them in case you come across a POSIX.1 system that doesn't
1593 support a time zone information database.
1595 The first format is used when there is no Daylight Saving Time (or
1596 summer time) in the local time zone:
1598 @smallexample
1599 @r{@var{std} @var{offset}}
1600 @end smallexample
1602 The @var{std} string specifies the name of the time zone.  It must be
1603 three or more characters long and must not contain a leading colon or
1604 embedded digits, commas, or plus or minus signs.  There is no space
1605 character separating the time zone name from the @var{offset}, so these
1606 restrictions are necessary to parse the specification correctly.
1608 The @var{offset} specifies the time value one must add to the local time
1609 to get a Coordinated Universal Time value.  It has syntax like
1610 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]].  This
1611 is positive if the local time zone is west of the Prime Meridian and
1612 negative if it is east.  The hour must be between @code{0} and
1613 @code{23}, and the minute and seconds between @code{0} and @code{59}.
1615 For example, here is how we would specify Eastern Standard Time, but
1616 without any daylight saving time alternative:
1618 @smallexample
1619 EST+5
1620 @end smallexample
1622 The second format is used when there is Daylight Saving Time:
1624 @smallexample
1625 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
1626 @end smallexample
1628 The initial @var{std} and @var{offset} specify the standard time zone, as
1629 described above.  The @var{dst} string and @var{offset} specify the name
1630 and offset for the corresponding daylight saving time zone; if the
1631 @var{offset} is omitted, it defaults to one hour ahead of standard time.
1633 The remainder of the specification describes when daylight saving time is
1634 in effect.  The @var{start} field is when daylight saving time goes into
1635 effect and the @var{end} field is when the change is made back to standard
1636 time.  The following formats are recognized for these fields:
1638 @table @code
1639 @item J@var{n}
1640 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
1641 February 29 is never counted, even in leap years.
1643 @item @var{n}
1644 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
1645 February 29 is counted in leap years.
1647 @item M@var{m}.@var{w}.@var{d}
1648 This specifies day @var{d} of week @var{w} of month @var{m}.  The day
1649 @var{d} must be between @code{0} (Sunday) and @code{6}.  The week
1650 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
1651 first week in which day @var{d} occurs, and week @code{5} specifies the
1652 @emph{last} @var{d} day in the month.  The month @var{m} should be
1653 between @code{1} and @code{12}.
1654 @end table
1656 The @var{time} fields specify when, in the local time currently in
1657 effect, the change to the other time occurs.  If omitted, the default is
1658 @code{02:00:00}.
1660 For example, here is how one would specify the Eastern time zone in the
1661 United States, including the appropriate daylight saving time and its dates
1662 of applicability.  The normal offset from UTC is 5 hours; since this is
1663 west of the prime meridian, the sign is positive.  Summer time begins on
1664 the first Sunday in April at 2:00am, and ends on the last Sunday in October
1665 at 2:00am.
1667 @smallexample
1668 EST+5EDT,M4.1.0/2,M10.5.0/2
1669 @end smallexample
1671 The schedule of daylight saving time in any particular jurisdiction has
1672 changed over the years.  To be strictly correct, the conversion of dates
1673 and times in the past should be based on the schedule that was in effect
1674 then.  However, this format has no facilities to let you specify how the
1675 schedule has changed from year to year.  The most you can do is specify
1676 one particular schedule---usually the present day schedule---and this is
1677 used to convert any date, no matter when.  For precise time zone
1678 specifications, it is best to use the time zone information database
1679 (see below).
1681 The third format looks like this:
1683 @smallexample
1684 :@var{characters}
1685 @end smallexample
1687 Each operating system interprets this format differently; in the GNU C
1688 library, @var{characters} is the name of a file which describes the time
1689 zone.
1691 @pindex /etc/localtime
1692 @pindex localtime
1693 If the @code{TZ} environment variable does not have a value, the
1694 operation chooses a time zone by default.  In the GNU C library, the
1695 default time zone is like the specification @samp{TZ=:/etc/localtime}
1696 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how GNU C library
1697 was configured; @pxref{Installation}).  Other C libraries use their own
1698 rule for choosing the default time zone, so there is little we can say
1699 about them.
1701 @cindex time zone database
1702 @pindex /share/lib/zoneinfo
1703 @pindex zoneinfo
1704 If @var{characters} begins with a slash, it is an absolute file name;
1705 otherwise the library looks for the file
1706 @w{@file{/share/lib/zoneinfo/@var{characters}}}.  The @file{zoneinfo}
1707 directory contains data files describing local time zones in many
1708 different parts of the world.  The names represent major cities, with
1709 subdirectories for geographical areas; for example,
1710 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
1711 These data files are installed by the system administrator, who also
1712 sets @file{/etc/localtime} to point to the data file for the local time
1713 zone.  The GNU C library comes with a large database of time zone
1714 information for most regions of the world, which is maintained by a
1715 community of volunteers and put in the public domain.
1717 @node Time Zone Functions
1718 @subsection Functions and Variables for Time Zones
1720 @comment time.h
1721 @comment POSIX.1
1722 @deftypevar {char *} tzname [2]
1723 The array @code{tzname} contains two strings, which are the standard
1724 names of the pair of time zones (standard and daylight
1725 saving) that the user has selected.  @code{tzname[0]} is the name of
1726 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
1727 is the name for the time zone when daylight saving time is in use (for
1728 example, @code{"EDT"}).  These correspond to the @var{std} and @var{dst}
1729 strings (respectively) from the @code{TZ} environment variable.  If
1730 daylight saving time is never used, @code{tzname[1]} is the empty string.
1732 The @code{tzname} array is initialized from the @code{TZ} environment
1733 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
1734 @code{mktime}, or @code{localtime} is called.  If multiple abbreviations
1735 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
1736 Time and Eastern Daylight Time), the array contains the most recent
1737 abbreviation.
1739 The @code{tzname} array is required for POSIX.1 compatibility, but in
1740 GNU programs it is better to use the @code{tm_zone} member of the
1741 broken-down time structure, since @code{tm_zone} reports the correct
1742 abbreviation even when it is not the latest one.
1744 Though the strings are declared as @code{char *} the user must stay away
1745 from modifying these strings.  Modifying the strings will almost certainly
1746 lead to trouble.
1748 @end deftypevar
1750 @comment time.h
1751 @comment POSIX.1
1752 @deftypefun void tzset (void)
1753 The @code{tzset} function initializes the @code{tzname} variable from
1754 the value of the @code{TZ} environment variable.  It is not usually
1755 necessary for your program to call this function, because it is called
1756 automatically when you use the other time conversion functions that
1757 depend on the time zone.
1758 @end deftypefun
1760 The following variables are defined for compatibility with System V
1761 Unix.  Like @code{tzname}, these variables are set by calling
1762 @code{tzset} or the other time conversion functions.
1764 @comment time.h
1765 @comment SVID
1766 @deftypevar {long int} timezone
1767 This contains the difference between UTC and the latest local standard
1768 time, in seconds west of UTC.  For example, in the U.S. Eastern time
1769 zone, the value is @code{5*60*60}.  Unlike the @code{tm_gmtoff} member
1770 of the broken-down time structure, this value is not adjusted for
1771 daylight saving, and its sign is reversed.  In GNU programs it is better
1772 to use @code{tm_gmtoff}, since it contains the correct offset even when
1773 it is not the latest one.
1774 @end deftypevar
1776 @comment time.h
1777 @comment SVID
1778 @deftypevar int daylight
1779 This variable has a nonzero value if daylight savings time rules apply.
1780 A nonzero value does not necessarily mean that daylight savings time is
1781 now in effect; it means only that daylight savings time is sometimes in
1782 effect.
1783 @end deftypevar
1785 @node Time Functions Example
1786 @subsection Time Functions Example
1788 Here is an example program showing the use of some of the local time and
1789 calendar time functions.
1791 @smallexample
1792 @include strftim.c.texi
1793 @end smallexample
1795 It produces output like this:
1797 @smallexample
1798 Wed Jul 31 13:02:36 1991
1799 Today is Wednesday, July 31.
1800 The time is 01:02 PM.
1801 @end smallexample
1804 @node Setting an Alarm
1805 @section Setting an Alarm
1807 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
1808 process to interrupt itself at some future time.  They do this by setting a
1809 timer; when the timer expires, the process receives a signal.
1811 @cindex setting an alarm
1812 @cindex interval timer, setting
1813 @cindex alarms, setting
1814 @cindex timers, setting
1815 Each process has three independent interval timers available:
1817 @itemize @bullet
1818 @item
1819 A real-time timer that counts clock time.  This timer sends a
1820 @code{SIGALRM} signal to the process when it expires.
1821 @cindex real-time timer
1822 @cindex timer, real-time
1824 @item
1825 A virtual timer that counts CPU time used by the process.  This timer
1826 sends a @code{SIGVTALRM} signal to the process when it expires.
1827 @cindex virtual timer
1828 @cindex timer, virtual
1830 @item
1831 A profiling timer that counts both CPU time used by the process, and CPU
1832 time spent in system calls on behalf of the process.  This timer sends a
1833 @code{SIGPROF} signal to the process when it expires.
1834 @cindex profiling timer
1835 @cindex timer, profiling
1837 This timer is useful for profiling in interpreters.  The interval timer
1838 mechanism does not have the fine granularity necessary for profiling
1839 native code.
1840 @c @xref{profil} !!!
1841 @end itemize
1843 You can only have one timer of each kind set at any given time.  If you
1844 set a timer that has not yet expired, that timer is simply reset to the
1845 new value.
1847 You should establish a handler for the appropriate alarm signal using
1848 @code{signal} or @code{sigaction} before issuing a call to @code{setitimer}
1849 or @code{alarm}.  Otherwise, an unusual chain of events could cause the
1850 timer to expire before your program establishes the handler, and in that
1851 case it would be terminated, since that is the default action for the alarm
1852 signals.  @xref{Signal Handling}.
1854 The @code{setitimer} function is the primary means for setting an alarm.
1855 This facility is declared in the header file @file{sys/time.h}.  The
1856 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
1857 simpler interface for setting the real-time timer.
1858 @pindex unistd.h
1859 @pindex sys/time.h
1861 @comment sys/time.h
1862 @comment BSD
1863 @deftp {Data Type} {struct itimerval}
1864 This structure is used to specify when a timer should expire.  It contains
1865 the following members:
1866 @table @code
1867 @item struct timeval it_interval
1868 This is the interval between successive timer interrupts.  If zero, the
1869 alarm will only be sent once.
1871 @item struct timeval it_value
1872 This is the interval to the first timer interrupt.  If zero, the alarm is
1873 disabled.
1874 @end table
1876 The @code{struct timeval} data type is described in @ref{High-Resolution
1877 Calendar}.
1878 @end deftp
1880 @comment sys/time.h
1881 @comment BSD
1882 @deftypefun int setitimer (int @var{which}, struct itimerval *@var{new}, struct itimerval *@var{old})
1883 The @code{setitimer} function sets the timer specified by @var{which}
1884 according to @var{new}.  The @var{which} argument can have a value of
1885 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
1887 If @var{old} is not a null pointer, @code{setitimer} returns information
1888 about any previous unexpired timer of the same kind in the structure it
1889 points to.
1891 The return value is @code{0} on success and @code{-1} on failure.  The
1892 following @code{errno} error conditions are defined for this function:
1894 @table @code
1895 @item EINVAL
1896 The timer interval was too large.
1897 @end table
1898 @end deftypefun
1900 @comment sys/time.h
1901 @comment BSD
1902 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
1903 The @code{getitimer} function stores information about the timer specified
1904 by @var{which} in the structure pointed at by @var{old}.
1906 The return value and error conditions are the same as for @code{setitimer}.
1907 @end deftypefun
1909 @comment sys/time.h
1910 @comment BSD
1911 @table @code
1912 @item ITIMER_REAL
1913 @findex ITIMER_REAL
1914 This constant can be used as the @var{which} argument to the
1915 @code{setitimer} and @code{getitimer} functions to specify the real-time
1916 timer.
1918 @comment sys/time.h
1919 @comment BSD
1920 @item ITIMER_VIRTUAL
1921 @findex ITIMER_VIRTUAL
1922 This constant can be used as the @var{which} argument to the
1923 @code{setitimer} and @code{getitimer} functions to specify the virtual
1924 timer.
1926 @comment sys/time.h
1927 @comment BSD
1928 @item ITIMER_PROF
1929 @findex ITIMER_PROF
1930 This constant can be used as the @var{which} argument to the
1931 @code{setitimer} and @code{getitimer} functions to specify the profiling
1932 timer.
1933 @end table
1935 @comment unistd.h
1936 @comment POSIX.1
1937 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
1938 The @code{alarm} function sets the real-time timer to expire in
1939 @var{seconds} seconds.  If you want to cancel any existing alarm, you
1940 can do this by calling @code{alarm} with a @var{seconds} argument of
1941 zero.
1943 The return value indicates how many seconds remain before the previous
1944 alarm would have been sent.  If there is no previous alarm, @code{alarm}
1945 returns zero.
1946 @end deftypefun
1948 The @code{alarm} function could be defined in terms of @code{setitimer}
1949 like this:
1951 @smallexample
1952 unsigned int
1953 alarm (unsigned int seconds)
1955   struct itimerval old, new;
1956   new.it_interval.tv_usec = 0;
1957   new.it_interval.tv_sec = 0;
1958   new.it_value.tv_usec = 0;
1959   new.it_value.tv_sec = (long int) seconds;
1960   if (setitimer (ITIMER_REAL, &new, &old) < 0)
1961     return 0;
1962   else
1963     return old.it_value.tv_sec;
1965 @end smallexample
1967 There is an example showing the use of the @code{alarm} function in
1968 @ref{Handler Returns}.
1970 If you simply want your process to wait for a given number of seconds,
1971 you should use the @code{sleep} function.  @xref{Sleeping}.
1973 You shouldn't count on the signal arriving precisely when the timer
1974 expires.  In a multiprocessing environment there is typically some
1975 amount of delay involved.
1977 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
1978 functions are derived from BSD Unix, while the @code{alarm} function is
1979 specified by the POSIX.1 standard.  @code{setitimer} is more powerful than
1980 @code{alarm}, but @code{alarm} is more widely used.
1982 @node Sleeping
1983 @section Sleeping
1985 The function @code{sleep} gives a simple way to make the program wait
1986 for short periods of time.  If your program doesn't use signals (except
1987 to terminate), then you can expect @code{sleep} to wait reliably for
1988 the specified amount of time.  Otherwise, @code{sleep} can return sooner
1989 if a signal arrives; if you want to wait for a given period regardless
1990 of signals, use @code{select} (@pxref{Waiting for I/O}) and don't
1991 specify any descriptors to wait for.
1992 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
1994 @comment unistd.h
1995 @comment POSIX.1
1996 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
1997 The @code{sleep} function waits for @var{seconds} or until a signal
1998 is delivered, whichever happens first.
2000 If @code{sleep} function returns because the requested time has
2001 elapsed, it returns a value of zero.  If it returns because of delivery
2002 of a signal, its return value is the remaining time in the sleep period.
2004 The @code{sleep} function is declared in @file{unistd.h}.
2005 @end deftypefun
2007 Resist the temptation to implement a sleep for a fixed amount of time by
2008 using the return value of @code{sleep}, when nonzero, to call
2009 @code{sleep} again.  This will work with a certain amount of accuracy as
2010 long as signals arrive infrequently.  But each signal can cause the
2011 eventual wakeup time to be off by an additional second or so.  Suppose a
2012 few signals happen to arrive in rapid succession by bad luck---there is
2013 no limit on how much this could shorten or lengthen the wait.
2015 Instead, compute the time at which the program should stop waiting, and
2016 keep trying to wait until that time.  This won't be off by more than a
2017 second.  With just a little more work, you can use @code{select} and
2018 make the waiting period quite accurate.  (Of course, heavy system load
2019 can cause unavoidable additional delays---unless the machine is
2020 dedicated to one application, there is no way you can avoid this.)
2022 On some systems, @code{sleep} can do strange things if your program uses
2023 @code{SIGALRM} explicitly.  Even if @code{SIGALRM} signals are being
2024 ignored or blocked when @code{sleep} is called, @code{sleep} might
2025 return prematurely on delivery of a @code{SIGALRM} signal.  If you have
2026 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
2027 signal is delivered while the process is sleeping, the action taken
2028 might be just to cause @code{sleep} to return instead of invoking your
2029 handler.  And, if @code{sleep} is interrupted by delivery of a signal
2030 whose handler requests an alarm or alters the handling of @code{SIGALRM},
2031 this handler and @code{sleep} will interfere.
2033 On the GNU system, it is safe to use @code{sleep} and @code{SIGALRM} in
2034 the same program, because @code{sleep} does not work by means of
2035 @code{SIGALRM}.
2037 @comment time.h
2038 @comment POSIX.1
2039 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
2040 If the resolution of seconds is not enough the @code{nanosleep} function
2041 can be used.  As the name suggests the sleeping period can be specified
2042 in nanoseconds.  The actual period of waiting time might be longer since
2043 the requested time in the @var{requested_time} parameter is rounded up
2044 to the next integer multiple of the actual resolution of the system.
2046 If the function returns because the time has elapsed the return value is
2047 zero.  If the function return @math{-1} the global variable @var{errno}
2048 is set to the following values:
2050 @table @code
2051 @item EINTR
2052 The call was interrupted because a signal was delivered to the thread.
2053 If the @var{remaining} parameter is not the null pointer the structure
2054 pointed to by @var{remaining} is updated to contain the remaining time.
2056 @item EINVAL
2057 The nanosecond value in the @var{requested_time} parameter contains an
2058 illegal value.  Either the value is negative or greater than or equal to
2059 1000 million.
2060 @end table
2062 This function is a cancelation point in multi-threaded programs.  This
2063 is a problem if the thread allocates some resources (like memory, file
2064 descriptors, semaphores or whatever) at the time @code{nanosleep} is
2065 called.  If the thread gets canceled these resources stay allocated
2066 until the program ends.  To avoid this calls to @code{nanosleep} should
2067 be protected using cancelation handlers.
2068 @c ref pthread_cleanup_push / pthread_cleanup_pop
2070 The @code{nanosleep} function is declared in @file{time.h}.
2071 @end deftypefun
2073 @node Resource Usage
2074 @section Resource Usage
2076 @pindex sys/resource.h
2077 The function @code{getrusage} and the data type @code{struct rusage}
2078 are used for examining the usage figures of a process.  They are declared
2079 in @file{sys/resource.h}.
2081 @comment sys/resource.h
2082 @comment BSD
2083 @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
2084 This function reports the usage totals for processes specified by
2085 @var{processes}, storing the information in @code{*@var{rusage}}.
2087 In most systems, @var{processes} has only two valid values:
2089 @table @code
2090 @comment sys/resource.h
2091 @comment BSD
2092 @item RUSAGE_SELF
2093 Just the current process.
2095 @comment sys/resource.h
2096 @comment BSD
2097 @item RUSAGE_CHILDREN
2098 All child processes (direct and indirect) that have terminated already.
2099 @end table
2101 In the GNU system, you can also inquire about a particular child process
2102 by specifying its process ID.
2104 The return value of @code{getrusage} is zero for success, and @code{-1}
2105 for failure.
2107 @table @code
2108 @item EINVAL
2109 The argument @var{processes} is not valid.
2110 @end table
2111 @end deftypefun
2113 One way of getting usage figures for a particular child process is with
2114 the function @code{wait4}, which returns totals for a child when it
2115 terminates.  @xref{BSD Wait Functions}.
2117 @comment sys/resource.h
2118 @comment BSD
2119 @deftp {Data Type} {struct rusage}
2120 This data type records a collection usage amounts for various sorts of
2121 resources.  It has the following members, and possibly others:
2123 @table @code
2124 @item struct timeval ru_utime
2125 Time spent executing user instructions.
2127 @item struct timeval ru_stime
2128 Time spent in operating system code on behalf of @var{processes}.
2130 @item long int ru_maxrss
2131 The maximum resident set size used, in kilobytes.  That is, the maximum
2132 number of kilobytes that @var{processes} used in real memory simultaneously.
2134 @item long int ru_ixrss
2135 An integral value expressed in kilobytes times ticks of execution, which
2136 indicates the amount of memory used by text that was shared with other
2137 processes.
2139 @item long int ru_idrss
2140 An integral value expressed the same way, which is the amount of
2141 unshared memory used in data.
2143 @item long int ru_isrss
2144 An integral value expressed the same way, which is the amount of
2145 unshared memory used in stack space.
2147 @item long int ru_minflt
2148 The number of page faults which were serviced without requiring any I/O.
2150 @item long int ru_majflt
2151 The number of page faults which were serviced by doing I/O.
2153 @item long int ru_nswap
2154 The number of times @var{processes} was swapped entirely out of main memory.
2156 @item long int ru_inblock
2157 The number of times the file system had to read from the disk on behalf
2158 of @var{processes}.
2160 @item long int ru_oublock
2161 The number of times the file system had to write to the disk on behalf
2162 of @var{processes}.
2164 @item long int ru_msgsnd
2165 Number of IPC messages sent.
2167 @item long ru_msgrcv
2168 Number of IPC messages received.
2170 @item long int ru_nsignals
2171 Number of signals received.
2173 @item long int ru_nvcsw
2174 The number of times @var{processes} voluntarily invoked a context switch
2175 (usually to wait for some service).
2177 @item long int ru_nivcsw
2178 The number of times an involuntary context switch took place (because
2179 the time slice expired, or another process of higher priority became
2180 runnable).
2181 @end table
2182 @end deftp
2184 An additional historical function for examining usage figures,
2185 @code{vtimes}, is supported but not documented here.  It is declared in
2186 @file{sys/vtimes.h}.
2188 @node Limits on Resources
2189 @section Limiting Resource Usage
2190 @cindex resource limits
2191 @cindex limits on resource usage
2192 @cindex usage limits
2194 You can specify limits for the resource usage of a process.  When the
2195 process tries to exceed a limit, it may get a signal, or the system call
2196 by which it tried to do so may fail, depending on the limit.  Each
2197 process initially inherits its limit values from its parent, but it can
2198 subsequently change them.
2200 @pindex sys/resource.h
2201 The symbols in this section are defined in @file{sys/resource.h}.
2203 @comment sys/resource.h
2204 @comment BSD
2205 @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
2206 Read the current value and the maximum value of resource @var{resource}
2207 and store them in @code{*@var{rlp}}.
2209 The return value is @code{0} on success and @code{-1} on failure.  The
2210 only possible @code{errno} error condition is @code{EFAULT}.
2212 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
2213 32 bits system this function is in fact @code{getrlimit64}.  I.e., the
2214 LFS interface transparently replaces the old interface.
2215 @end deftypefun
2217 @comment sys/resource.h
2218 @comment Unix98
2219 @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
2220 This function is similar to the @code{getrlimit} but its second
2221 parameter is a pointer to a variable of type @code{struct rlimit64}
2222 which allows this function to read values which wouldn't fit in the
2223 member of a @code{struct rlimit}.
2225 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
2226 bits machine this function is available under the name @code{getrlimit}
2227 and so transparently replaces the old interface.
2228 @end deftypefun
2230 @comment sys/resource.h
2231 @comment BSD
2232 @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
2233 Store the current value and the maximum value of resource @var{resource}
2234 in @code{*@var{rlp}}.
2236 The return value is @code{0} on success and @code{-1} on failure.  The
2237 following @code{errno} error condition is possible:
2239 @table @code
2240 @item EPERM
2241 You tried to change the maximum permissible limit value,
2242 but you don't have privileges to do so.
2243 @end table
2245 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
2246 32 bits system this function is in fact @code{setrlimit64}.  I.e., the
2247 LFS interface transparently replaces the old interface.
2248 @end deftypefun
2250 @comment sys/resource.h
2251 @comment Unix98
2252 @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
2253 This function is similar to the @code{setrlimit} but its second
2254 parameter is a pointer to a variable of type @code{struct rlimit64}
2255 which allows this function to set values which wouldn't fit in the
2256 member of a @code{struct rlimit}.
2258 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
2259 bits machine this function is available under the name @code{setrlimit}
2260 and so transparently replaces the old interface.
2261 @end deftypefun
2263 @comment sys/resource.h
2264 @comment BSD
2265 @deftp {Data Type} {struct rlimit}
2266 This structure is used with @code{getrlimit} to receive limit values,
2267 and with @code{setrlimit} to specify limit values.  It has two fields:
2269 @table @code
2270 @item rlim_t rlim_cur
2271 The current value of the limit in question.
2272 This is also called the ``soft limit''.
2273 @cindex soft limit
2275 @item rlim_t rlim_max
2276 The maximum permissible value of the limit in question.  You cannot set
2277 the current value of the limit to a larger number than this maximum.
2278 Only the super user can change the maximum permissible value.
2279 This is also called the ``hard limit''.
2280 @cindex hard limit
2281 @end table
2283 In @code{getrlimit}, the structure is an output; it receives the current
2284 values.  In @code{setrlimit}, it specifies the new values.
2285 @end deftp
2287 For the LFS functions a similar type is defined in @file{sys/resource.h}.
2289 @comment sys/resource.h
2290 @comment Unix98
2291 @deftp {Data Type} {struct rlimit64}
2292 This structure is used with @code{getrlimit64} to receive limit values,
2293 and with @code{setrlimit64} to specify limit values.  It has two fields:
2295 @table @code
2296 @item rlim64_t rlim_cur
2297 The current value of the limit in question.
2298 This is also called the ``soft limit''.
2300 @item rlim64_t rlim_max
2301 The maximum permissible value of the limit in question.  You cannot set
2302 the current value of the limit to a larger number than this maximum.
2303 Only the super user can change the maximum permissible value.
2304 This is also called the ``hard limit''.
2305 @end table
2307 In @code{getrlimit64}, the structure is an output; it receives the current
2308 values.  In @code{setrlimit64}, it specifies the new values.
2309 @end deftp
2311 Here is a list of resources that you can specify a limit for.
2312 Those that are sizes are measured in bytes.
2314 @table @code
2315 @comment sys/resource.h
2316 @comment BSD
2317 @item RLIMIT_CPU
2318 @vindex RLIMIT_CPU
2319 The maximum amount of cpu time the process can use.  If it runs for
2320 longer than this, it gets a signal: @code{SIGXCPU}.  The value is
2321 measured in seconds.  @xref{Operation Error Signals}.
2323 @comment sys/resource.h
2324 @comment BSD
2325 @item RLIMIT_FSIZE
2326 @vindex RLIMIT_FSIZE
2327 The maximum size of file the process can create.  Trying to write a
2328 larger file causes a signal: @code{SIGXFSZ}.  @xref{Operation Error
2329 Signals}.
2331 @comment sys/resource.h
2332 @comment BSD
2333 @item RLIMIT_DATA
2334 @vindex RLIMIT_DATA
2335 The maximum size of data memory for the process.  If the process tries
2336 to allocate data memory beyond this amount, the allocation function
2337 fails.
2339 @comment sys/resource.h
2340 @comment BSD
2341 @item RLIMIT_STACK
2342 @vindex RLIMIT_STACK
2343 The maximum stack size for the process.  If the process tries to extend
2344 its stack past this size, it gets a @code{SIGSEGV} signal.
2345 @xref{Program Error Signals}.
2347 @comment sys/resource.h
2348 @comment BSD
2349 @item RLIMIT_CORE
2350 @vindex RLIMIT_CORE
2351 The maximum size core file that this process can create.  If the process
2352 terminates and would dump a core file larger than this maximum size,
2353 then no core file is created.  So setting this limit to zero prevents
2354 core files from ever being created.
2356 @comment sys/resource.h
2357 @comment BSD
2358 @item RLIMIT_RSS
2359 @vindex RLIMIT_RSS
2360 The maximum amount of physical memory that this process should get.
2361 This parameter is a guide for the system's scheduler and memory
2362 allocator; the system may give the process more memory when there is a
2363 surplus.
2365 @comment sys/resource.h
2366 @comment BSD
2367 @item RLIMIT_MEMLOCK
2368 The maximum amount of memory that can be locked into physical memory (so
2369 it will never be paged out).
2371 @comment sys/resource.h
2372 @comment BSD
2373 @item RLIMIT_NPROC
2374 The maximum number of processes that can be created with the same user ID.
2375 If you have reached the limit for your user ID, @code{fork} will fail
2376 with @code{EAGAIN}.  @xref{Creating a Process}.
2378 @comment sys/resource.h
2379 @comment BSD
2380 @item RLIMIT_NOFILE
2381 @vindex RLIMIT_NOFILE
2382 @itemx RLIMIT_OFILE
2383 @vindex RLIMIT_OFILE
2384 The maximum number of files that the process can open.  If it tries to
2385 open more files than this, it gets error code @code{EMFILE}.
2386 @xref{Error Codes}.  Not all systems support this limit; GNU does, and
2387 4.4 BSD does.
2389 @comment sys/resource.h
2390 @comment BSD
2391 @item RLIM_NLIMITS
2392 @vindex RLIM_NLIMITS
2393 The number of different resource limits.  Any valid @var{resource}
2394 operand must be less than @code{RLIM_NLIMITS}.
2395 @end table
2397 @comment sys/resource.h
2398 @comment BSD
2399 @deftypevr Constant int RLIM_INFINITY
2400 This constant stands for a value of ``infinity'' when supplied as
2401 the limit value in @code{setrlimit}.
2402 @end deftypevr
2404 @c ??? Someone want to finish these?
2405 Two historical functions for setting resource limits, @code{ulimit} and
2406 @code{vlimit}, are not documented here.  The latter is declared in
2407 @file{sys/vlimit.h} and comes from BSD.
2409 @node Priority
2410 @section Process Priority
2411 @cindex process priority
2412 @cindex priority of a process
2414 @pindex sys/resource.h
2415 When several processes try to run, their respective priorities determine
2416 what share of the CPU each process gets.  This section describes how you
2417 can read and set the priority of a process.  All these functions and
2418 macros are declared in @file{sys/resource.h}.
2420 The range of valid priority values depends on the operating system, but
2421 typically it runs from @code{-20} to @code{20}.  A lower priority value
2422 means the process runs more often.  These constants describe the range of
2423 priority values:
2425 @table @code
2426 @comment sys/resource.h
2427 @comment BSD
2428 @item PRIO_MIN
2429 @vindex PRIO_MIN
2430 The smallest valid priority value.
2432 @comment sys/resource.h
2433 @comment BSD
2434 @item PRIO_MAX
2435 @vindex PRIO_MAX
2436 The largest valid priority value.
2437 @end table
2439 @comment sys/resource.h
2440 @comment BSD
2441 @deftypefun int getpriority (int @var{class}, int @var{id})
2442 Read the priority of a class of processes; @var{class} and @var{id}
2443 specify which ones (see below).  If the processes specified do not all
2444 have the same priority, this returns the smallest value that any of them
2445 has.
2447 The return value is the priority value on success, and @code{-1} on
2448 failure.  The following @code{errno} error condition are possible for
2449 this function:
2451 @table @code
2452 @item ESRCH
2453 The combination of @var{class} and @var{id} does not match any existing
2454 process.
2456 @item EINVAL
2457 The value of @var{class} is not valid.
2458 @end table
2460 When the return value is @code{-1}, it could indicate failure, or it
2461 could be the priority value.  The only way to make certain is to set
2462 @code{errno = 0} before calling @code{getpriority}, then use @code{errno
2463 != 0} afterward as the criterion for failure.
2464 @end deftypefun
2466 @comment sys/resource.h
2467 @comment BSD
2468 @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{priority})
2469 Set the priority of a class of processes to @var{priority}; @var{class}
2470 and @var{id} specify which ones (see below).
2472 The return value is @code{0} on success and @code{-1} on failure.  The
2473 following @code{errno} error condition are defined for this function:
2475 @table @code
2476 @item ESRCH
2477 The combination of @var{class} and @var{id} does not match any existing
2478 process.
2480 @item EINVAL
2481 The value of @var{class} is not valid.
2483 @item EPERM
2484 You tried to set the priority of some other user's process, and you
2485 don't have privileges for that.
2487 @item EACCES
2488 You tried to lower the priority of a process, and you don't have
2489 privileges for that.
2490 @end table
2491 @end deftypefun
2493 The arguments @var{class} and @var{id} together specify a set of
2494 processes you are interested in.  These are the possible values for
2495 @var{class}:
2497 @table @code
2498 @comment sys/resource.h
2499 @comment BSD
2500 @item PRIO_PROCESS
2501 @vindex PRIO_PROCESS
2502 Read or set the priority of one process.  The argument @var{id} is a
2503 process ID.
2505 @comment sys/resource.h
2506 @comment BSD
2507 @item PRIO_PGRP
2508 @vindex PRIO_PGRP
2509 Read or set the priority of one process group.  The argument @var{id} is
2510 a process group ID.
2512 @comment sys/resource.h
2513 @comment BSD
2514 @item PRIO_USER
2515 @vindex PRIO_USER
2516 Read or set the priority of one user's processes.  The argument @var{id}
2517 is a user ID.
2518 @end table
2520 If the argument @var{id} is 0, it stands for the current process,
2521 current process group, or the current user, according to @var{class}.
2523 @c ??? I don't know where we should say this comes from.
2524 @comment Unix
2525 @comment dunno.h
2526 @deftypefun int nice (int @var{increment})
2527 Increment the priority of the current process by @var{increment}.
2528 The return value is the same as for @code{setpriority}.
2530 Here is an equivalent definition for @code{nice}:
2532 @smallexample
2534 nice (int increment)
2536   int old = getpriority (PRIO_PROCESS, 0);
2537   return setpriority (PRIO_PROCESS, 0, old + increment);
2539 @end smallexample
2540 @end deftypefun