1 @node Date and Time, Resource Usage And Limitation, Arithmetic, Top
2 @c %MENU% Functions for getting the date and time and formatting them nicely
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:
13 Functions for measuring elapsed CPU time are discussed in @ref{Processor
17 Functions for measuring absolute clock or calendar time are discussed in
21 Functions for setting alarms and timers are discussed in @ref{Setting
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.
32 For functions to examine and control a process' CPU time, see
33 @xref{Resource Usage And Limitation}.
37 @section Processor Time
39 If you're trying to optimize your program or measure its efficiency, it's
40 very useful to be able to know how much @dfn{processor time} or @dfn{CPU
41 time} it has used at any given point. Processor time is different from
42 actual wall clock time because it doesn't include any time spent waiting
43 for I/O or when some other process is running. Processor time is
44 represented by the data type @code{clock_t}, and is given as a number of
45 @dfn{clock ticks} relative to an arbitrary base time marking the beginning
46 of a single program invocation.
48 @cindex processor time
51 @cindex time, elapsed CPU
54 * Basic CPU Time:: The @code{clock} function.
55 * Detailed CPU Time:: The @code{times} function.
59 @subsection Basic CPU Time Inquiry
61 To get the elapsed CPU time used by a process, you can use the
62 @code{clock} function. This facility is declared in the header file
66 In typical usage, you call the @code{clock} function at the beginning and
67 end of the interval you want to time, subtract the values, and then divide
68 by @code{CLOCKS_PER_SEC} (the number of clock ticks per second), like this:
78 @dots{} /* @r{Do the work.} */
80 elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
84 Different computers and operating systems vary wildly in how they keep
85 track of processor time. It's common for the internal processor clock
86 to have a resolution somewhere between hundredth and millionth of a
89 In the GNU system, @code{clock_t} is equivalent to @code{long int} and
90 @code{CLOCKS_PER_SEC} is an integer value. But in other systems, both
91 @code{clock_t} and the type of the macro @code{CLOCKS_PER_SEC} can be
92 either integer or floating-point types. Casting processor time values
93 to @code{double}, as in the example above, makes sure that operations
94 such as arithmetic and printing work properly and consistently no matter
95 what the underlying representation is.
97 Note that the clock can wrap around. On a 32bit system with
98 @code{CLOCKS_PER_SEC} set to one million this function will return the
99 same value approximately every 72 minutes.
103 @deftypevr Macro int CLOCKS_PER_SEC
104 The value of this macro is the number of clock ticks per second measured
105 by the @code{clock} function. POSIX requires that this value is one
106 million independent of the actual resolution.
111 @deftypevr Macro int CLK_TCK
112 This is an obsolete name for @code{CLOCKS_PER_SEC}.
117 @deftp {Data Type} clock_t
118 This is the type of the value returned by the @code{clock} function.
119 Values of type @code{clock_t} are in units of clock ticks.
124 @deftypefun clock_t clock (void)
125 This function returns the elapsed processor time. The base time is
126 arbitrary but doesn't change within a single process. If the processor
127 time is not available or cannot be represented, @code{clock} returns the
128 value @code{(clock_t)(-1)}.
132 @node Detailed CPU Time
133 @subsection Detailed Elapsed CPU Time Inquiry
135 The @code{times} function returns more detailed information about
136 elapsed processor time in a @w{@code{struct tms}} object. You should
137 include the header file @file{sys/times.h} to use this facility.
142 @deftp {Data Type} {struct tms}
143 The @code{tms} structure is used to return information about process
144 times. It contains at least the following members:
147 @item clock_t tms_utime
148 This is the CPU time used in executing the instructions of the calling
151 @item clock_t tms_stime
152 This is the CPU time used by the system on behalf of the calling process.
154 @item clock_t tms_cutime
155 This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
156 values of all terminated child processes of the calling process, whose
157 status has been reported to the parent process by @code{wait} or
158 @code{waitpid}; see @ref{Process Completion}. In other words, it
159 represents the total CPU time used in executing the instructions of all
160 the terminated child processes of the calling process, excluding child
161 processes which have not yet been reported by @code{wait} or
164 @item clock_t tms_cstime
165 This is similar to @code{tms_cutime}, but represents the total CPU time
166 used by the system on behalf of all the terminated child processes of the
170 All of the times are given in clock ticks. These are absolute values; in a
171 newly created process, they are all zero. @xref{Creating a Process}.
176 @deftypefun clock_t times (struct tms *@var{buffer})
177 The @code{times} function stores the processor time information for
178 the calling process in @var{buffer}.
180 The return value is the same as the value of @code{clock()}: the elapsed
181 real time relative to an arbitrary base. The base is a constant within a
182 particular process, and typically represents the time since system
183 start-up. A value of @code{(clock_t)(-1)} is returned to indicate failure.
186 @strong{Portability Note:} The @code{clock} function described in
187 @ref{Basic CPU Time}, is specified by the @w{ISO C} standard. The
188 @code{times} function is a feature of POSIX.1. In the GNU system, the
189 value returned by the @code{clock} function is equivalent to the sum of
190 the @code{tms_utime} and @code{tms_stime} fields returned by
194 @section Calendar Time
196 This section describes facilities for keeping track of points in time.
197 This is called calendar time and sometimes absolute time.
198 @cindex time, absolute
199 @cindex time, calendar
200 @cindex date and time
202 The GNU C library represents calendar time three ways:
206 @dfn{Simple time} (the @code{time_t} data type) is a compact
207 representation, typically giving the number of seconds elapsed since
208 some implementation-specific base time.
212 There is also a @dfn{high-resolution time} representation (the @code{struct
213 timeval} data type) that includes fractions of a second. Use this time
214 representation instead of simple time when you need greater
216 @cindex high-resolution time
219 @dfn{Local time} or @dfn{broken-down time} (the @code{struct tm} data
220 type) represents the date and time as a set of components specifying the
221 year, month, and so on in the Gregorian calendar, for a specific time
222 zone. This time representation is usually used only to communicate with
225 @cindex broken-down time
226 @cindex Gregorian calendar
227 @cindex calendar, Gregorian
231 * Simple Calendar Time:: Facilities for manipulating calendar time.
232 * High-Resolution Calendar:: A time representation with greater precision.
233 * Broken-down Time:: Facilities for manipulating local time.
234 * High Accuracy Clock:: Maintaining a high accuracy system clock.
235 * Formatting Date and Time:: Converting times to strings.
236 * Parsing Date and Time:: Convert textual time and date information back
237 into broken-down time values.
238 * TZ Variable:: How users specify the time zone.
239 * Time Zone Functions:: Functions to examine or specify the time zone.
240 * Time Functions Example:: An example program showing use of some of
244 @node Simple Calendar Time
245 @subsection Simple Calendar Time
247 This section describes the @code{time_t} data type for representing calendar
248 time as simple time, and the functions which operate on simple time objects.
249 These facilities are declared in the header file @file{time.h}.
255 @deftp {Data Type} time_t
256 This is the data type used to represent simple time. Sometimes, it also
257 represents an elapsed time.
258 When interpreted as an absolute time
259 value, it represents the number of seconds elapsed since 00:00:00 on
260 January 1, 1970, Coordinated Universal Time. (This time is sometimes
261 referred to as the @dfn{epoch}.) POSIX requires that this count
262 not include leap seconds, but on some hosts this count includes leap seconds
263 if you set @code{TZ} to certain values (@pxref{TZ Variable}).
265 Note that a simple time has no concept of local time zone. Time @var{N}
266 is the same instant in time regardless of where on the globe the
269 In the GNU C library, @code{time_t} is equivalent to @code{long int}.
270 In other systems, @code{time_t} might be either an integer or
276 @deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
277 The @code{difftime} function returns the number of seconds elapsed
278 between time @var{time1} and time @var{time0}, as a value of type
279 @code{double}. The difference ignores leap seconds unless leap
280 second support is enabled.
282 In the GNU system, you can simply subtract @code{time_t} values. But on
283 other systems, the @code{time_t} data type might use some other encoding
284 where subtraction doesn't work directly.
289 @deftypefun time_t time (time_t *@var{result})
290 The @code{time} function returns the current time as a value of type
291 @code{time_t}. If the argument @var{result} is not a null pointer, the
292 time value is also stored in @code{*@var{result}}. If the calendar
293 time is not available, the value @w{@code{(time_t)(-1)}} is returned.
296 @c The GNU C library implements stime() with a call to settimeofday() on
300 @deftypefun int stime (time_t *@var{newtime})
301 @code{stime} sets the system clock, i.e. it tells the system that the
302 present absolute time is @var{newtime}, where @code{newtime} is
303 interpreted as described in the above definition of @code{time_t}.
305 @code{settimeofday} is a newer function which sets the system clock to
306 better than one second precision. @code{settimeofday} is generally a
307 better choice than @code{stime}. @xref{High-Resolution Calendar}.
309 Only the superuser can set the system clock.
311 If the function succeeds, the return value is zero. Otherwise, it is
312 @code{-1} and @code{errno} is set accordingly:
316 The process is not superuser.
322 @node High-Resolution Calendar
323 @subsection High-Resolution Calendar
325 The @code{time_t} data type used to represent simple times has a
326 resolution of only one second. Some applications need more precision.
328 So, the GNU C library also contains functions which are capable of
329 representing calendar times to a higher resolution than one second. The
330 functions and the associated data types described in this section are
331 declared in @file{sys/time.h}.
336 @deftp {Data Type} {struct timeval}
337 The @code{struct timeval} structure represents a calendar time. It
338 has the following members:
341 @item long int tv_sec
342 This represents the number of seconds since the epoch. It is equivalent
343 to a normal @code{time_t} value.
345 @item long int tv_usec
346 This is the fractional second value, represented as the number of
349 Some times struct timeval values are used for time intervals. Then the
350 @code{tv_sec} member is the number of seconds in the interval, and
351 @code{tv_usec} is the number of additional microseconds.
357 @deftp {Data Type} {struct timezone}
358 The @code{struct timezone} structure is used to hold minimal information
359 about the local time zone. It has the following members:
362 @item int tz_minuteswest
363 This is the number of minutes west of UTC.
366 If nonzero, Daylight Saving Time applies during some part of the year.
369 The @code{struct timezone} type is obsolete and should never be used.
370 Instead, use the facilities described in @ref{Time Zone Functions}.
373 It is often necessary to subtract two values of type @w{@code{struct
374 timeval}}. Here is the best way to do this. It works even on some
375 peculiar operating systems where the @code{tv_sec} member has an
379 /* @r{Subtract the `struct timeval' values X and Y,}
380 @r{storing the result in RESULT.}
381 @r{Return 1 if the difference is negative, otherwise 0.} */
384 timeval_subtract (result, x, y)
385 struct timeval *result, *x, *y;
387 /* @r{Perform the carry for the later subtraction by updating @var{y}.} */
388 if (x->tv_usec < y->tv_usec) @{
389 int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
390 y->tv_usec -= 1000000 * nsec;
393 if (x->tv_usec - y->tv_usec > 1000000) @{
394 int nsec = (x->tv_usec - y->tv_usec) / 1000000;
395 y->tv_usec += 1000000 * nsec;
399 /* @r{Compute the time remaining to wait.}
400 @r{@code{tv_usec} is certainly positive.} */
401 result->tv_sec = x->tv_sec - y->tv_sec;
402 result->tv_usec = x->tv_usec - y->tv_usec;
404 /* @r{Return 1 if result is negative.} */
405 return x->tv_sec < y->tv_sec;
411 @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
412 The @code{gettimeofday} function returns the current date and time in the
413 @code{struct timeval} structure indicated by @var{tp}. Information about the
414 time zone is returned in the structure pointed at @var{tzp}. If the @var{tzp}
415 argument is a null pointer, time zone information is ignored.
417 The return value is @code{0} on success and @code{-1} on failure. The
418 following @code{errno} error condition is defined for this function:
422 The operating system does not support getting time zone information, and
423 @var{tzp} is not a null pointer. The GNU operating system does not
424 support using @w{@code{struct timezone}} to represent time zone
425 information; that is an obsolete feature of 4.3 BSD.
426 Instead, use the facilities described in @ref{Time Zone Functions}.
432 @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
433 The @code{settimeofday} function sets the current date and time
434 according to the arguments. As for @code{gettimeofday}, time zone
435 information is ignored if @var{tzp} is a null pointer.
437 You must be a privileged user in order to use @code{settimeofday}.
439 Some kernels automatically set the system clock from some source such as
440 a hardware clock when they start up. Others, including Linux, place the
441 system clock in an ``invalid'' state (in which attempts to read the time
442 fail). A call of @code{stime} removes the system clock from an invalid
443 state, and system startup scripts typically run a program that calls
446 @code{settimeofday} causes a sudden jump forwards or backwards, which
447 can cause a variety of problems in a system. Use @code{adjtime} (below)
448 to make a smooth transition from one time to another by temporarily
449 speeding up or slowing down the clock.
451 With a Linux kernel, @code{adjtimex} does the same thing and can also
452 make permanent changes to the speed of the system clock so it doesn't
453 need to be corrected as often.
455 The return value is @code{0} on success and @code{-1} on failure. The
456 following @code{errno} error conditions are defined for this function:
460 This process cannot set the time because it is not privileged.
463 The operating system does not support setting time zone information, and
464 @var{tzp} is not a null pointer.
468 @c On Linux, GNU libc implements adjtime() as a call to adjtimex().
471 @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
472 This function speeds up or slows down the system clock in order to make
473 gradual adjustments in the current time. This ensures that the time
474 reported by the system clock is always monotonically increasing, which
475 might not happen if you simply set the current time.
477 The @var{delta} argument specifies a relative adjustment to be made to
478 the current time. If negative, the system clock is slowed down for a
479 while until it has lost this much time. If positive, the system clock
480 is speeded up for a while.
482 If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
483 function returns information about any previous time adjustment that
484 has not yet completed.
486 This function is typically used to synchronize the clocks of computers
487 in a local network. You must be a privileged user to use it.
489 With a Linux kernel, you can use the @code{adjtimex} function to
490 permanently change the clock speed.
492 The return value is @code{0} on success and @code{-1} on failure. The
493 following @code{errno} error condition is defined for this function:
497 You do not have privilege to set the time.
501 @strong{Portability Note:} The @code{gettimeofday}, @code{settimeofday},
502 and @code{adjtime} functions are derived from BSD.
505 Symbols for the following function are declared in @file{sys/timex.h}.
509 @deftypefun int adjtimex (struct timex *@var{timex})
511 @code{adjtimex} is functionally identical to @code{ntp_adjtime}.
512 @xref{High Accuracy Clock}.
514 This function is present only with a Linux kernel.
518 @node Broken-down Time
519 @subsection Broken-down Time
520 @cindex broken-down time
521 @cindex calendar time and broken-down time
523 Calendar time is represented as an amount of time since a fixed base
524 time. This is convenient for calculation, but has no relation to the
525 way people normally think of dates and times. By contrast,
526 @dfn{broken-down time} is a binary representation separated into year,
527 month, day, and so on. Broken-down time values are not useful for
528 calculations, but they are useful for printing human readable time.
530 A broken-down time value is always relative to a choice of time
531 zone, and it also indicates which time zone was used.
533 The symbols in this section are declared in the header file @file{time.h}.
537 @deftp {Data Type} {struct tm}
538 This is the data type used to represent a broken-down time. The structure
539 contains at least the following members, which can appear in any order:
543 This is the number of seconds after the minute, normally in the range
544 @code{0} through @code{59}. (The actual upper limit is @code{60}, to allow
545 for leap seconds if leap second support is available.)
549 This is the number of minutes after the hour, in the range @code{0} through
553 This is the number of hours past midnight, in the range @code{0} through
557 This is the day of the month, in the range @code{1} through @code{31}.
560 This is the number of months since January, in the range @code{0} through
564 This is the number of years since @code{1900}.
567 This is the number of days since Sunday, in the range @code{0} through
571 This is the number of days since January 1, in the range @code{0} through
575 @cindex Daylight Saving Time
577 This is a flag that indicates whether Daylight Saving Time is (or was, or
578 will be) in effect at the time described. The value is positive if
579 Daylight Saving Time is in effect, zero if it is not, and negative if the
580 information is not available.
582 @item long int tm_gmtoff
583 This field describes the time zone that was used to compute this
584 broken-down time value, including any adjustment for daylight saving; it
585 is the number of seconds that you must add to UTC to get local time.
586 You can also think of this as the number of seconds east of UTC. For
587 example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
588 The @code{tm_gmtoff} field is derived from BSD and is a GNU library
589 extension; it is not visible in a strict @w{ISO C} environment.
591 @item const char *tm_zone
592 This field is the name for the time zone that was used to compute this
593 broken-down time value. Like @code{tm_gmtoff}, this field is a BSD and
594 GNU extension, and is not visible in a strict @w{ISO C} environment.
600 @deftypefun {struct tm *} localtime (const time_t *@var{time})
601 The @code{localtime} function converts the simple time pointed to by
602 @var{time} to broken-down time representation, expressed relative to the
603 user's specified time zone.
605 The return value is a pointer to a static broken-down time structure, which
606 might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
607 or @code{localtime}. (But no other library function overwrites the contents
610 The return value is the null pointer if @var{time} cannot be represented
611 as a broken-down time; typically this is because the year cannot fit into
614 Calling @code{localtime} has one other effect: it sets the variable
615 @code{tzname} with information about the current time zone. @xref{Time
619 Using the @code{localtime} function is a big problem in multi-threaded
620 programs. The result is returned in a static buffer and this is used in
621 all threads. POSIX.1c introduced a variant of this function.
625 @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
626 The @code{localtime_r} function works just like the @code{localtime}
627 function. It takes a pointer to a variable containing a simple time
628 and converts it to the broken-down time format.
630 But the result is not placed in a static buffer. Instead it is placed
631 in the object of type @code{struct tm} to which the parameter
632 @var{resultp} points.
634 If the conversion is successful the function returns a pointer to the
635 object the result was written into, i.e., it returns @var{resultp}.
641 @deftypefun {struct tm *} gmtime (const time_t *@var{time})
642 This function is similar to @code{localtime}, except that the broken-down
643 time is expressed as Coordinated Universal Time (UTC) (formerly called
644 Greenwich Mean Time (GMT)) rather than relative to a local time zone.
648 As for the @code{localtime} function we have the problem that the result
649 is placed in a static variable. POSIX.1c also provides a replacement for
654 @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
655 This function is similar to @code{localtime_r}, except that it converts
656 just like @code{gmtime} the given time as Coordinated Universal Time.
658 If the conversion is successful the function returns a pointer to the
659 object the result was written into, i.e., it returns @var{resultp}.
665 @deftypefun time_t mktime (struct tm *@var{brokentime})
666 The @code{mktime} function is used to convert a broken-down time structure
667 to a simple time representation. It also ``normalizes'' the contents of
668 the broken-down time structure, by filling in the day of week and day of
669 year based on the other date and time components.
671 The @code{mktime} function ignores the specified contents of the
672 @code{tm_wday} and @code{tm_yday} members of the broken-down time
673 structure. It uses the values of the other components to determine the
674 calendar time; it's permissible for these components to have
675 unnormalized values outside their normal ranges. The last thing that
676 @code{mktime} does is adjust the components of the @var{brokentime}
677 structure (including the @code{tm_wday} and @code{tm_yday}).
679 If the specified broken-down time cannot be represented as a simple time,
680 @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
681 the contents of @var{brokentime}.
683 Calling @code{mktime} also sets the variable @code{tzname} with
684 information about the current time zone. @xref{Time Zone Functions}.
689 @deftypefun time_t timelocal (struct tm *@var{brokentime})
691 @code{timelocal} is functionally identical to @code{mktime}, but more
692 mnemonically named. Note that it is the inverse of the @code{localtime}
695 @strong{Portability note:} @code{mktime} is essentially universally
696 available. @code{timelocal} is rather rare.
702 @deftypefun time_t timegm (struct tm *@var{brokentime})
704 @code{timegm} is functionally identical to @code{mktime} except it
705 always takes the input values to be Coordinated Universal Time (UTC)
706 regardless of any local time zone setting.
708 Note that @code{timegm} is the inverse of @code{gmtime}.
710 @strong{Portability note:} @code{mktime} is essentially universally
711 available. @code{timegm} is rather rare. For the most portable
712 conversion from a UTC broken-down time to a simple time, set
713 the @code{TZ} environment variable to UTC, call @code{mktime}, then set
720 @node High Accuracy Clock
721 @subsection High Accuracy Clock
723 @cindex time, high precision
724 @cindex clock, high accuracy
726 @c On Linux, GNU libc implements ntp_gettime() and npt_adjtime() as calls
728 The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
729 interface to monitor and manipulate the system clock to maintain high
730 accuracy time. For example, you can fine tune the speed of the clock
731 or synchronize it with another time source.
733 A typical use of these functions is by a server implementing the Network
734 Time Protocol to synchronize the clocks of multiple systems and high
737 These functions are declared in @file{sys/timex.h}.
739 @tindex struct ntptimeval
740 @deftp {Data Type} {struct ntptimeval}
741 This structure is used to monitor kernel time. It contains the
744 @item struct timeval time
745 This is the current time. The @code{struct timeval} data type is
746 described in @ref{High-Resolution Calendar}.
748 @item long int maxerror
749 This is the maximum error, measured in microseconds. Unless updated
750 via @code{ntp_adjtime} periodically, this value will reach some
751 platform-specific maximum value.
753 @item long int esterror
754 This is the estimated error, measured in microseconds. This value can
755 be set by @code{ntp_adjtime} to indicate the estimated offset of the
756 local clock against the true time.
762 @deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
763 The @code{ntp_gettime} function sets the structure pointed to by
764 @var{tptr} to current values. The elements of the structure afterwards
765 contain the values the timer implementation in the kernel assumes. They
766 might or might not be correct. If they are not a @code{ntp_adjtime}
769 The return value is @code{0} on success and other values on failure. The
770 following @code{errno} error conditions are defined for this function:
774 The precision clock model is not properly set up at the moment, thus the
775 clock must be considered unsynchronized, and the values should be
781 @deftp {Data Type} {struct timex}
782 This structure is used to control and monitor the system clock. It
783 contains the following members:
785 @item unsigned int modes
786 This variable controls whether and which values are set. Several
787 symbolic constants have to be combined with @emph{binary or} to specify
788 the effective mode. These constants start with @code{MOD_}.
790 @item long int offset
791 This value indicates the current offset of the local clock from the true
792 time. The value is given in microseconds. If bit @code{MOD_OFFSET} is
793 set in @code{modes}, the offset (and possibly other dependent values) can
794 be set. The offset's absolute value must not exceed @code{MAXPHASE}.
797 @item long int frequency
798 This value indicates the difference in frequency between the true time
799 and the local clock. The value is expressed as scaled PPM (parts per
800 million, 0.0001%). The scaling is @code{1 << SHIFT_USEC}. The value
801 can be set with bit @code{MOD_FREQUENCY}, but the absolute value must
802 not exceed @code{MAXFREQ}.
804 @item long int maxerror
805 This is the maximum error, measured in microseconds. A new value can be
806 set using bit @code{MOD_MAXERROR}. Unless updated via
807 @code{ntp_adjtime} periodically, this value will increase steadily
808 and reach some platform-specific maximum value.
810 @item long int esterror
811 This is the estimated error, measured in microseconds. This value can
812 be set using bit @code{MOD_ESTERROR}.
815 This variable reflects the various states of the clock machinery. There
816 are symbolic constants for the significant bits, starting with
817 @code{STA_}. Some of these flags can be updated using the
818 @code{MOD_STATUS} bit.
820 @item long int constant
821 This value represents the bandwidth or stiffness of the PLL (phase
822 locked loop) implemented in the kernel. The value can be changed using
823 bit @code{MOD_TIMECONST}.
825 @item long int precision
826 This value represents the accuracy or the maximum error when reading the
827 system clock. The value is expressed in microseconds.
829 @item long int tolerance
830 This value represents the maximum frequency error of the system clock in
831 scaled PPM. This value is used to increase the @code{maxerror} every
834 @item struct timeval time
838 The time between clock ticks in microseconds. A clock tick is a
839 periodic timer interrupt on which the system clock is based.
841 @item long int ppsfreq
842 This is the first of a few optional variables that are present only if
843 the system clock can use a PPS (pulse per second) signal to discipline
844 the local clock. The value is expressed in scaled PPM and it denotes
845 the difference in frequency between the local clock and the PPS signal.
847 @item long int jitter
848 This value expresses a median filtered average of the PPS signal's
849 dispersion in microseconds.
852 This value is a binary exponent for the duration of the PPS calibration
853 interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
855 @item long int stabil
856 This value represents the median filtered dispersion of the PPS
857 frequency in scaled PPM.
859 @item long int jitcnt
860 This counter represents the number of pulses where the jitter exceeded
861 the allowed maximum @code{MAXTIME}.
863 @item long int calcnt
864 This counter reflects the number of successful calibration intervals.
866 @item long int errcnt
867 This counter represents the number of calibration errors (caused by
868 large offsets or jitter).
870 @item long int stbcnt
871 This counter denotes the number of of calibrations where the stability
872 exceeded the threshold.
878 @deftypefun int ntp_adjtime (struct timex *@var{tptr})
879 The @code{ntp_adjtime} function sets the structure specified by
880 @var{tptr} to current values.
882 In addition, @code{ntp_adjtime} updates some settings to match what you
883 pass to it in *@var{tptr}. Use the @code{modes} element of *@var{tptr}
884 to select what settings to update. You can set @code{offset},
885 @code{freq}, @code{maxerror}, @code{esterror}, @code{status},
886 @code{constant}, and @code{tick}.
888 @code{modes} = zero means set nothing.
890 Only the superuser can update settings.
892 @c On Linux, ntp_adjtime() also does the adjtime() function if you set
893 @c modes = ADJ_OFFSET_SINGLESHOT (in fact, that is how GNU libc implements
894 @c adjtime()). But this should be considered an internal function because
895 @c it's so inconsistent with the rest of what ntp_adjtime() does and is
896 @c forced in an ugly way into the struct timex. So we don't document it
897 @c and instead document adjtime() as the way to achieve the function.
899 The return value is @code{0} on success and other values on failure. The
900 following @code{errno} error conditions are defined for this function:
904 The high accuracy clock model is not properly set up at the moment, thus the
905 clock must be considered unsynchronized, and the values should be
906 treated with care. Another reason could be that the specified new values
910 The process specified a settings update, but is not superuser.
914 For more details see RFC1305 (Network Time Protocol, Version 3) and
917 @strong{Portability note:} Early versions of the GNU C library did not
918 have this function but did have the synonymous @code{adjtimex}.
923 @node Formatting Date and Time
924 @subsection Formatting Date and Time
926 The functions described in this section format time values as strings.
927 These functions are declared in the header file @file{time.h}.
932 @deftypefun {char *} asctime (const struct tm *@var{brokentime})
933 The @code{asctime} function converts the broken-down time value that
934 @var{brokentime} points to into a string in a standard format:
937 "Tue May 21 13:46:22 1991\n"
940 The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
941 @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
943 The abbreviations for the months are: @samp{Jan}, @samp{Feb},
944 @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
945 @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
947 The return value points to a statically allocated string, which might be
948 overwritten by subsequent calls to @code{asctime} or @code{ctime}.
949 (But no other library function overwrites the contents of this
955 @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
956 This function is similar to @code{asctime} but instead of placing the
957 result in a static buffer it writes the string in the buffer pointed to
958 by the parameter @var{buffer}. This buffer should have room
959 for at least 26 bytes, including the terminating null.
961 If no error occurred the function returns a pointer to the string the
962 result was written into, i.e., it returns @var{buffer}. Otherwise
969 @deftypefun {char *} ctime (const time_t *@var{time})
970 The @code{ctime} function is similar to @code{asctime}, except that the
971 time value is specified as a @code{time_t} simple time value rather
972 than in broken-down local time format. It is equivalent to
975 asctime (localtime (@var{time}))
978 @code{ctime} sets the variable @code{tzname}, because @code{localtime}
979 does so. @xref{Time Zone Functions}.
984 @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
985 This function is similar to @code{ctime}, only that it places the result
986 in the string pointed to by @var{buffer}. It is equivalent to (written
987 using gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
990 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
993 If no error occurred the function returns a pointer to the string the
994 result was written into, i.e., it returns @var{buffer}. Otherwise
1001 @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
1002 This function is similar to the @code{sprintf} function (@pxref{Formatted
1003 Input}), but the conversion specifications that can appear in the format
1004 template @var{template} are specialized for printing components of the date
1005 and time @var{brokentime} according to the locale currently specified for
1006 time conversion (@pxref{Locales}).
1008 Ordinary characters appearing in the @var{template} are copied to the
1009 output string @var{s}; this can include multibyte character sequences.
1010 Conversion specifiers are introduced by a @samp{%} character, followed
1011 by an optional flag which can be one of the following. These flags
1012 are all GNU extensions. The first three affect only the output of
1017 The number is padded with spaces.
1020 The number is not padded at all.
1023 The number is padded with zeros even if the format specifies padding
1027 The output uses uppercase characters, but only if this is possible
1028 (@pxref{Case Conversion}).
1031 The default action is to pad the number with zeros to keep it a constant
1032 width. Numbers that do not have a range indicated below are never
1033 padded, since there is no natural width for them.
1035 Following the flag an optional specification of the width is possible.
1036 This is specified in decimal notation. If the natural size of the
1037 output is of the field has less than the specified number of characters,
1038 the result is written right adjusted and space padded to the given
1041 An optional modifier can follow the optional flag and width
1042 specification. The modifiers, which are POSIX.2 extensions, are:
1046 Use the locale's alternate representation for date and time. This
1047 modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
1048 @code{%y} and @code{%Y} format specifiers. In a Japanese locale, for
1049 example, @code{%Ex} might yield a date format based on the Japanese
1053 Use the locale's alternate numeric symbols for numbers. This modifier
1054 applies only to numeric format specifiers.
1057 If the format supports the modifier but no alternate representation
1058 is available, it is ignored.
1060 The conversion specifier ends with a format specifier taken from the
1061 following list. The whole @samp{%} sequence is replaced in the output
1066 The abbreviated weekday name according to the current locale.
1069 The full weekday name according to the current locale.
1072 The abbreviated month name according to the current locale.
1075 The full month name according to the current locale.
1078 The preferred date and time representation for the current locale.
1081 The century of the year. This is equivalent to the greatest integer not
1082 greater than the year divided by 100.
1084 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1087 The day of the month as a decimal number (range @code{01} through @code{31}).
1090 The date using the format @code{%m/%d/%y}.
1092 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1095 The day of the month like with @code{%d}, but padded with blank (range
1096 @code{ 1} through @code{31}).
1098 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1101 The date using the format @code{%Y-%m-%d}. This is the form specified
1102 in the @w{ISO 8601} standard and is the preferred form for all uses.
1104 This format is a @w{ISO C99} extension.
1107 The year corresponding to the ISO week number, but without the century
1108 (range @code{00} through @code{99}). This has the same format and value
1109 as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
1110 to the previous or next year, that year is used instead.
1112 This format was introduced in @w{ISO C99}.
1115 The year corresponding to the ISO week number. This has the same format
1116 and value as @code{%Y}, except that if the ISO week number (see
1117 @code{%V}) belongs to the previous or next year, that year is used
1120 This format was introduced in @w{ISO C99} but was previously available
1124 The abbreviated month name according to the current locale. The action
1125 is the same as for @code{%b}.
1127 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1130 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1134 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1138 The day of the year as a decimal number (range @code{001} through @code{366}).
1141 The hour as a decimal number, using a 24-hour clock like @code{%H}, but
1142 padded with blank (range @code{ 0} through @code{23}).
1144 This format is a GNU extension.
1147 The hour as a decimal number, using a 12-hour clock like @code{%I}, but
1148 padded with blank (range @code{ 1} through @code{12}).
1150 This format is a GNU extension.
1153 The month as a decimal number (range @code{01} through @code{12}).
1156 The minute as a decimal number (range @code{00} through @code{59}).
1159 A single @samp{\n} (newline) character.
1161 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1164 Either @samp{AM} or @samp{PM}, according to the given time value; or the
1165 corresponding strings for the current locale. Noon is treated as
1166 @samp{PM} and midnight as @samp{AM}.
1169 We currently have a problem with makeinfo. Write @samp{AM} and @samp{am}
1170 both results in `am'. I.e., the difference in case is not visible anymore.
1173 Either @samp{am} or @samp{pm}, according to the given time value; or the
1174 corresponding strings for the current locale, printed in lowercase
1175 characters. Noon is treated as @samp{pm} and midnight as @samp{am}.
1177 This format was introduced in @w{ISO C99} but was previously available
1181 The complete time using the AM/PM format of the current locale.
1183 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1186 The hour and minute in decimal numbers using the format @code{%H:%M}.
1188 This format was introduced in @w{ISO C99} but was previously available
1192 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1193 Leap seconds are not counted unless leap second support is available.
1195 This format is a GNU extension.
1198 The seconds as a decimal number (range @code{00} through @code{60}).
1201 A single @samp{\t} (tabulator) character.
1203 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1206 The time using decimal numbers using the format @code{%H:%M:%S}.
1208 This format is a POSIX.2 extension.
1211 The day of the week as a decimal number (range @code{1} through
1212 @code{7}), Monday being @code{1}.
1214 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1217 The week number of the current year as a decimal number (range @code{00}
1218 through @code{53}), starting with the first Sunday as the first day of
1219 the first week. Days preceding the first Sunday in the year are
1220 considered to be in week @code{00}.
1223 The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
1224 through @code{53}). ISO weeks start with Monday and end with Sunday.
1225 Week @code{01} of a year is the first week which has the majority of its
1226 days in that year; this is equivalent to the week containing the year's
1227 first Thursday, and it is also equivalent to the week containing January
1228 4. Week @code{01} of a year can contain days from the previous year.
1229 The week before week @code{01} of a year is the last week (@code{52} or
1230 @code{53}) of the previous year even if it contains days from the new
1233 This format is a POSIX.2 extension and also appears in @w{ISO C99}.
1236 The day of the week as a decimal number (range @code{0} through
1237 @code{6}), Sunday being @code{0}.
1240 The week number of the current year as a decimal number (range @code{00}
1241 through @code{53}), starting with the first Monday as the first day of
1242 the first week. All days preceding the first Monday in the year are
1243 considered to be in week @code{00}.
1246 The preferred date representation for the current locale, but without the
1250 The preferred time representation for the current locale, but with no date.
1253 The year without a century as a decimal number (range @code{00} through
1254 @code{99}). This is equivalent to the year modulo 100.
1257 The year as a decimal number, using the Gregorian calendar. Years
1258 before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
1261 @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
1262 @code{-0600} or @code{+0100}), or nothing if no time zone is
1265 This format was introduced in @w{ISO C99} but was previously available
1268 A full @w{RFC 822} timestamp is generated by the format
1269 @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
1270 @w{@samp{"%a, %d %b %Y %T %z"}}).
1273 The time zone abbreviation (empty if the time zone can't be determined).
1276 A literal @samp{%} character.
1279 The @var{size} parameter can be used to specify the maximum number of
1280 characters to be stored in the array @var{s}, including the terminating
1281 null character. If the formatted time requires more than @var{size}
1282 characters, @code{strftime} returns zero and the contents of the array
1283 @var{s} are undefined. Otherwise the return value indicates the
1284 number of characters placed in the array @var{s}, not including the
1285 terminating null character.
1287 @emph{Warning:} This convention for the return value which is prescribed
1288 in @w{ISO C} can lead to problems in some situations. For certain
1289 format strings and certain locales the output really can be the empty
1290 string and this cannot be discovered by testing the return value only.
1291 E.g., in most locales the AM/PM time format is not supported (most of
1292 the world uses the 24 hour time representation). In such locales
1293 @code{"%p"} will return the empty string, i.e., the return value is
1294 zero. To detect situations like this something similar to the following
1295 code should be used:
1299 len = strftime (buf, bufsize, format, tp);
1300 if (len == 0 && buf[0] != '\0')
1302 /* Something went wrong in the strftime call. */
1307 If @var{s} is a null pointer, @code{strftime} does not actually write
1308 anything, but instead returns the number of characters it would have written.
1310 According to POSIX.1 every call to @code{strftime} implies a call to
1311 @code{tzset}. So the contents of the environment variable @code{TZ}
1312 is examined before any output is produced.
1314 For an example of @code{strftime}, see @ref{Time Functions Example}.
1319 @deftypefun size_t wcsftime (wchar_t *@var{s}, size_t @var{size}, const wchar_t *@var{template}, const struct tm *@var{brokentime})
1320 The @code{wcsftime} function is equivalent to the @code{strftime}
1321 function with the difference that it operates on wide character
1322 strings. The buffer where the result is stored, pointed to by @var{s},
1323 must be an array of wide characters. The parameter @var{size} which
1324 specifies the size of the output buffer gives the number of wide
1325 character, not the number of bytes.
1327 Also the format string @var{template} is a wide character string. Since
1328 all characters needed to specify the format string are in the basic
1329 character set it is portably possible to write format strings in the C
1330 source code using the @code{L"..."} notation. The parameter
1331 @var{brokentime} has the same meaning as in the @code{strftime} call.
1333 The @code{wcsftime} function supports the same flags, modifiers, and
1334 format specifiers as the @code{strftime} function.
1336 The return value of @code{wcsftime} is the number of wide characters
1337 stored in @code{s}. When more characters would have to be written than
1338 can be placed in the buffer @var{s} the return value is zero, with the
1339 same problems indicated in the @code{strftime} documentation.
1342 @node Parsing Date and Time
1343 @subsection Convert textual time and date information back
1345 The @w{ISO C} standard does not specify any functions which can convert
1346 the output of the @code{strftime} function back into a binary format.
1347 This led to a variety of more-or-less successful implementations with
1348 different interfaces over the years. Then the Unix standard was
1349 extended by the addition of two functions: @code{strptime} and
1350 @code{getdate}. Both have strange interfaces but at least they are
1354 * Low-Level Time String Parsing:: Interpret string according to given format.
1355 * General Time String Parsing:: User-friendly function to parse data and
1359 @node Low-Level Time String Parsing
1360 @subsubsection Interpret string according to given format
1362 he first function is rather low-level. It is nevertheless frequently
1363 used in software since it is better known. Its interface and
1364 implementation are heavily influenced by the @code{getdate} function,
1365 which is defined and implemented in terms of calls to @code{strptime}.
1369 @deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1370 The @code{strptime} function parses the input string @var{s} according
1371 to the format string @var{fmt} and stores its results in the
1374 The input string could be generated by a @code{strftime} call or
1375 obtained any other way. It does not need to be in a human-recognizable
1376 format; e.g. a date passed as @code{"02:1999:9"} is acceptable, even
1377 though it is ambiguous without context. As long as the format string
1378 @var{fmt} matches the input string the function will succeed.
1380 The format string consists of the same components as the format string
1381 of the @code{strftime} function. The only difference is that the flags
1382 @code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1383 @comment Is this really the intention? --drepper
1384 Several of the distinct formats of @code{strftime} do the same work in
1385 @code{strptime} since differences like case of the input do not matter.
1386 For reasons of symmetry all formats are supported, though.
1388 The modifiers @code{E} and @code{O} are also allowed everywhere the
1389 @code{strftime} function allows them.
1396 The weekday name according to the current locale, in abbreviated form or
1402 The month name according to the current locale, in abbreviated form or
1406 The date and time representation for the current locale.
1409 Like @code{%c} but the locale's alternative date and time format is used.
1412 The century of the year.
1414 It makes sense to use this format only if the format string also
1415 contains the @code{%y} format.
1418 The locale's representation of the period.
1420 Unlike @code{%C} it sometimes makes sense to use this format since some
1421 cultures represent years relative to the beginning of eras instead of
1422 using the Gregorian years.
1426 The day of the month as a decimal number (range @code{1} through @code{31}).
1427 Leading zeroes are permitted but not required.
1431 Same as @code{%d} but using the locale's alternative numeric symbols.
1433 Leading zeroes are permitted but not required.
1436 Equivalent to @code{%m/%d/%y}.
1439 Equivalent to @code{%Y-%m-%d}, which is the @w{ISO 8601} date
1442 This is a GNU extension following an @w{ISO C99} extension to
1446 The year corresponding to the ISO week number, but without the century
1447 (range @code{00} through @code{99}).
1449 @emph{Note:} Currently, this is not fully implemented. The format is
1450 recognized, input is consumed but no field in @var{tm} is set.
1452 This format is a GNU extension following a GNU extension of @code{strftime}.
1455 The year corresponding to the ISO week number.
1457 @emph{Note:} Currently, this is not fully implemented. The format is
1458 recognized, input is consumed but no field in @var{tm} is set.
1460 This format is a GNU extension following a GNU extension of @code{strftime}.
1464 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1467 @code{%k} is a GNU extension following a GNU extension of @code{strftime}.
1470 Same as @code{%H} but using the locale's alternative numeric symbols.
1474 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1477 @code{%l} is a GNU extension following a GNU extension of @code{strftime}.
1480 Same as @code{%I} but using the locale's alternative numeric symbols.
1483 The day of the year as a decimal number (range @code{1} through @code{366}).
1485 Leading zeroes are permitted but not required.
1488 The month as a decimal number (range @code{1} through @code{12}).
1490 Leading zeroes are permitted but not required.
1493 Same as @code{%m} but using the locale's alternative numeric symbols.
1496 The minute as a decimal number (range @code{0} through @code{59}).
1498 Leading zeroes are permitted but not required.
1501 Same as @code{%M} but using the locale's alternative numeric symbols.
1505 Matches any white space.
1509 The locale-dependent equivalent to @samp{AM} or @samp{PM}.
1511 This format is not useful unless @code{%I} or @code{%l} is also used.
1512 Another complication is that the locale might not define these values at
1513 all and therefore the conversion fails.
1515 @code{%P} is a GNU extension following a GNU extension to @code{strftime}.
1518 The complete time using the AM/PM format of the current locale.
1520 A complication is that the locale might not define this format at all
1521 and therefore the conversion fails.
1524 The hour and minute in decimal numbers using the format @code{%H:%M}.
1526 @code{%R} is a GNU extension following a GNU extension to @code{strftime}.
1529 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1530 Leap seconds are not counted unless leap second support is available.
1532 @code{%s} is a GNU extension following a GNU extension to @code{strftime}.
1535 The seconds as a decimal number (range @code{0} through @code{61}).
1537 Leading zeroes are permitted but not required.
1539 Note the nonsense with @code{61}, as given in the Unix specification.
1540 This is a result of a decision to allow double leap seconds. These do
1541 not in fact exist but the myth persists.
1544 Same as @code{%S} but using the locale's alternative numeric symbols.
1547 Equivalent to the use of @code{%H:%M:%S} in this place.
1550 The day of the week as a decimal number (range @code{1} through
1551 @code{7}), Monday being @code{1}.
1553 Leading zeroes are permitted but not required.
1555 @emph{Note:} Currently, this is not fully implemented. The format is
1556 recognized, input is consumed but no field in @var{tm} is set.
1559 The week number of the current year as a decimal number (range @code{0}
1562 Leading zeroes are permitted but not required.
1565 Same as @code{%U} but using the locale's alternative numeric symbols.
1568 The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
1571 Leading zeroes are permitted but not required.
1573 @emph{Note:} Currently, this is not fully implemented. The format is
1574 recognized, input is consumed but no field in @var{tm} is set.
1577 The day of the week as a decimal number (range @code{0} through
1578 @code{6}), Sunday being @code{0}.
1580 Leading zeroes are permitted but not required.
1582 @emph{Note:} Currently, this is not fully implemented. The format is
1583 recognized, input is consumed but no field in @var{tm} is set.
1586 Same as @code{%w} but using the locale's alternative numeric symbols.
1589 The week number of the current year as a decimal number (range @code{0}
1592 Leading zeroes are permitted but not required.
1594 @emph{Note:} Currently, this is not fully implemented. The format is
1595 recognized, input is consumed but no field in @var{tm} is set.
1598 Same as @code{%W} but using the locale's alternative numeric symbols.
1601 The date using the locale's date format.
1604 Like @code{%x} but the locale's alternative data representation is used.
1607 The time using the locale's time format.
1610 Like @code{%X} but the locale's alternative time representation is used.
1613 The year without a century as a decimal number (range @code{0} through
1616 Leading zeroes are permitted but not required.
1618 Note that it is questionable to use this format without
1619 the @code{%C} format. The @code{strptime} function does regard input
1620 values in the range @math{68} to @math{99} as the years @math{1969} to
1621 @math{1999} and the values @math{0} to @math{68} as the years
1622 @math{2000} to @math{2068}. But maybe this heuristic fails for some
1625 Therefore it is best to avoid @code{%y} completely and use @code{%Y}
1629 The offset from @code{%EC} in the locale's alternative representation.
1632 The offset of the year (from @code{%C}) using the locale's alternative
1636 The year as a decimal number, using the Gregorian calendar.
1639 The full alternative year representation.
1642 Equivalent to the use of @code{%a, %d %b %Y %H:%M:%S %z} in this place.
1643 This is the full @w{ISO 8601} date and time format.
1648 @emph{Note:} Currently, this is not fully implemented. The format is
1649 recognized, input is consumed but no field in @var{tm} is set.
1652 A literal @samp{%} character.
1655 All other characters in the format string must have a matching character
1656 in the input string. Exceptions are white spaces in the input string
1657 which can match zero or more white space characters in the format string.
1659 The @code{strptime} function processes the input string from right to
1660 left. Each of the three possible input elements (white space, literal,
1661 or format) are handled one after the other. If the input cannot be
1662 matched to the format string the function stops. The remainder of the
1663 format and input strings are not processed.
1665 The function returns a pointer to the first character it was unable to
1666 process. If the input string contains more characters than required by
1667 the format string the return value points right after the last consumed
1668 input character. If the whole input string is consumed the return value
1669 points to the @code{NULL} byte at the end of the string. If an error
1670 occurs, i.e. @code{strptime} fails to match all of the format string,
1671 the function returns @code{NULL}.
1674 The specification of the function in the XPG standard is rather vague,
1675 leaving out a few important pieces of information. Most importantly, it
1676 does not specify what happens to those elements of @var{tm} which are
1677 not directly initialized by the different formats. The
1678 implementations on different Unix systems vary here.
1680 The GNU libc implementation does not touch those fields which are not
1681 directly initialized. Exceptions are the @code{tm_wday} and
1682 @code{tm_yday} elements, which are recomputed if any of the year, month,
1683 or date elements changed. This has two implications:
1687 Before calling the @code{strptime} function for a new input string, you
1688 should prepare the @var{tm} structure you pass. Normally this will mean
1689 initializing all values are to zero. Alternatively, you can set all
1690 fields to values like @code{INT_MAX}, allowing you to determine which
1691 elements were set by the function call. Zero does not work here since
1692 it is a valid value for many of the fields.
1694 Careful initialization is necessary if you want to find out whether a
1695 certain field in @var{tm} was initialized by the function call.
1698 You can construct a @code{struct tm} value with several consecutive
1699 @code{strptime} calls. A useful application of this is e.g. the parsing
1700 of two separate strings, one containing date information and the other
1701 time information. By parsing one after the other without clearing the
1702 structure in-between, you can construct a complete broken-down time.
1705 The following example shows a function which parses a string which is
1706 contains the date information in either US style or @w{ISO 8601} form:
1710 parse_date (const char *input, struct tm *tm)
1714 /* @r{First clear the result structure.} */
1715 memset (tm, '\0', sizeof (*tm));
1717 /* @r{Try the ISO format first.} */
1718 cp = strptime (input, "%F", tm);
1721 /* @r{Does not match. Try the US form.} */
1722 cp = strptime (input, "%D", tm);
1729 @node General Time String Parsing
1730 @subsubsection A More User-friendly Way to Parse Times and Dates
1732 The Unix standard defines another function for parsing date strings.
1733 The interface is weird, but if the function happens to suit your
1734 application it is just fine. It is problematic to use this function
1735 in multi-threaded programs or libraries, since it returns a pointer to
1736 a static variable, and uses a global variable and global state (an
1737 environment variable).
1742 This variable of type @code{int} contains the error code of the last
1743 unsuccessful call to @code{getdate}. Defined values are:
1747 The environment variable @code{DATEMSK} is not defined or null.
1749 The template file denoted by the @code{DATEMSK} environment variable
1752 Information about the template file cannot retrieved.
1754 The template file is not a regular file.
1756 An I/O error occurred while reading the template file.
1758 Not enough memory available to execute the function.
1760 The template file contains no matching template.
1762 The input date is invalid, but would match a template otherwise. This
1763 includes dates like February 31st, and dates which cannot be represented
1764 in a @code{time_t} variable.
1770 @deftypefun {struct tm *} getdate (const char *@var{string})
1771 The interface to @code{getdate} is the simplest possible for a function
1772 to parse a string and return the value. @var{string} is the input
1773 string and the result is returned in a statically-allocated variable.
1775 The details about how the string is processed are hidden from the user.
1776 In fact, they can be outside the control of the program. Which formats
1777 are recognized is controlled by the file named by the environment
1778 variable @code{DATEMSK}. This file should contain
1779 lines of valid format strings which could be passed to @code{strptime}.
1781 The @code{getdate} function reads these format strings one after the
1782 other and tries to match the input string. The first line which
1783 completely matches the input string is used.
1785 Elements not initialized through the format string retain the values
1786 present at the time of the @code{getdate} function call.
1788 The formats recognized by @code{getdate} are the same as for
1789 @code{strptime}. See above for an explanation. There are only a few
1790 extensions to the @code{strptime} behavior:
1794 If the @code{%Z} format is given the broken-down time is based on the
1795 current time of the timezone matched, not of the current timezone of the
1796 runtime environment.
1798 @emph{Note}: This is not implemented (currently). The problem is that
1799 timezone names are not unique. If a fixed timezone is assumed for a
1800 given string (say @code{EST} meaning US East Coast time), then uses for
1801 countries other than the USA will fail. So far we have found no good
1805 If only the weekday is specified the selected day depends on the current
1806 date. If the current weekday is greater or equal to the @code{tm_wday}
1807 value the current week's day is chosen, otherwise the day next week is chosen.
1810 A similar heuristic is used when only the month is given and not the
1811 year. If the month is greater than or equal to the current month, then
1812 the current year is used. Otherwise it wraps to next year. The first
1813 day of the month is assumed if one is not explicitly specified.
1816 The current hour, minute, and second are used if the appropriate value is
1817 not set through the format.
1820 If no date is given tomorrow's date is used if the time is
1821 smaller than the current time. Otherwise today's date is taken.
1824 It should be noted that the format in the template file need not only
1825 contain format elements. The following is a list of possible format
1826 strings (taken from the Unix standard):
1830 %A %B %d, %Y %H:%M:%S
1835 at %A the %dst of %B in %Y
1836 run job at %I %p,%B %dnd
1837 %A den %d. %B %Y %H.%M Uhr
1840 As you can see, the template list can contain very specific strings like
1841 @code{run job at %I %p,%B %dnd}. Using the above list of templates and
1842 assuming the current time is Mon Sep 22 12:19:47 EDT 1986 we can obtain the
1843 following results for the given input.
1845 @multitable {xxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1846 @item Input @tab Match @tab Result
1847 @item Mon @tab %a @tab Mon Sep 22 12:19:47 EDT 1986
1848 @item Sun @tab %a @tab Sun Sep 28 12:19:47 EDT 1986
1849 @item Fri @tab %a @tab Fri Sep 26 12:19:47 EDT 1986
1850 @item September @tab %B @tab Mon Sep 1 12:19:47 EDT 1986
1851 @item January @tab %B @tab Thu Jan 1 12:19:47 EST 1987
1852 @item December @tab %B @tab Mon Dec 1 12:19:47 EST 1986
1853 @item Sep Mon @tab %b %a @tab Mon Sep 1 12:19:47 EDT 1986
1854 @item Jan Fri @tab %b %a @tab Fri Jan 2 12:19:47 EST 1987
1855 @item Dec Mon @tab %b %a @tab Mon Dec 1 12:19:47 EST 1986
1856 @item Jan Wed 1989 @tab %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
1857 @item Fri 9 @tab %a %H @tab Fri Sep 26 09:00:00 EDT 1986
1858 @item Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
1859 @item 10:30 @tab %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
1860 @item 13:30 @tab %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
1863 The return value of the function is a pointer to a static variable of
1864 type @w{@code{struct tm}}, or a null pointer if an error occurred. The
1865 result is only valid until the next @code{getdate} call, making this
1866 function unusable in multi-threaded applications.
1868 The @code{errno} variable is @emph{not} changed. Error conditions are
1869 stored in the global variable @code{getdate_err}. See the
1870 description above for a list of the possible error values.
1872 @emph{Warning:} The @code{getdate} function should @emph{never} be
1873 used in SUID-programs. The reason is obvious: using the
1874 @code{DATEMSK} environment variable you can get the function to open
1875 any arbitrary file and chances are high that with some bogus input
1876 (such as a binary file) the program will crash.
1881 @deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
1882 The @code{getdate_r} function is the reentrant counterpart of
1883 @code{getdate}. It does not use the global variable @code{getdate_err}
1884 to signal an error, but instead returns an error code. The same error
1885 codes as described in the @code{getdate_err} documentation above are
1886 used, with 0 meaning success.
1888 Moreover, @code{getdate_r} stores the broken-down time in the variable
1889 of type @code{struct tm} pointed to by the second argument, rather than
1890 in a static variable.
1892 This function is not defined in the Unix standard. Nevertheless it is
1893 available on some other Unix systems as well.
1895 The warning against using @code{getdate} in SUID-programs applies to
1896 @code{getdate_r} as well.
1900 @subsection Specifying the Time Zone with @code{TZ}
1902 In POSIX systems, a user can specify the time zone by means of the
1903 @code{TZ} environment variable. For information about how to set
1904 environment variables, see @ref{Environment Variables}. The functions
1905 for accessing the time zone are declared in @file{time.h}.
1909 You should not normally need to set @code{TZ}. If the system is
1910 configured properly, the default time zone will be correct. You might
1911 set @code{TZ} if you are using a computer over a network from a
1912 different time zone, and would like times reported to you in the time
1913 zone local to you, rather than what is local to the computer.
1915 In POSIX.1 systems the value of the @code{TZ} variable can be in one of
1916 three formats. With the GNU C library, the most common format is the
1917 last one, which can specify a selection from a large database of time
1918 zone information for many regions of the world. The first two formats
1919 are used to describe the time zone information directly, which is both
1920 more cumbersome and less precise. But the POSIX.1 standard only
1921 specifies the details of the first two formats, so it is good to be
1922 familiar with them in case you come across a POSIX.1 system that doesn't
1923 support a time zone information database.
1925 The first format is used when there is no Daylight Saving Time (or
1926 summer time) in the local time zone:
1929 @r{@var{std} @var{offset}}
1932 The @var{std} string specifies the name of the time zone. It must be
1933 three or more characters long and must not contain a leading colon,
1934 embedded digits, commas, nor plus and minus signs. There is no space
1935 character separating the time zone name from the @var{offset}, so these
1936 restrictions are necessary to parse the specification correctly.
1938 The @var{offset} specifies the time value you must add to the local time
1939 to get a Coordinated Universal Time value. It has syntax like
1940 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]]. This
1941 is positive if the local time zone is west of the Prime Meridian and
1942 negative if it is east. The hour must be between @code{0} and
1943 @code{23}, and the minute and seconds between @code{0} and @code{59}.
1945 For example, here is how we would specify Eastern Standard Time, but
1946 without any Daylight Saving Time alternative:
1952 The second format is used when there is Daylight Saving Time:
1955 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
1958 The initial @var{std} and @var{offset} specify the standard time zone, as
1959 described above. The @var{dst} string and @var{offset} specify the name
1960 and offset for the corresponding Daylight Saving Time zone; if the
1961 @var{offset} is omitted, it defaults to one hour ahead of standard time.
1963 The remainder of the specification describes when Daylight Saving Time is
1964 in effect. The @var{start} field is when Daylight Saving Time goes into
1965 effect and the @var{end} field is when the change is made back to standard
1966 time. The following formats are recognized for these fields:
1970 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
1971 February 29 is never counted, even in leap years.
1974 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
1975 February 29 is counted in leap years.
1977 @item M@var{m}.@var{w}.@var{d}
1978 This specifies day @var{d} of week @var{w} of month @var{m}. The day
1979 @var{d} must be between @code{0} (Sunday) and @code{6}. The week
1980 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
1981 first week in which day @var{d} occurs, and week @code{5} specifies the
1982 @emph{last} @var{d} day in the month. The month @var{m} should be
1983 between @code{1} and @code{12}.
1986 The @var{time} fields specify when, in the local time currently in
1987 effect, the change to the other time occurs. If omitted, the default is
1990 For example, here is how you would specify the Eastern time zone in the
1991 United States, including the appropriate Daylight Saving Time and its dates
1992 of applicability. The normal offset from UTC is 5 hours; since this is
1993 west of the prime meridian, the sign is positive. Summer time begins on
1994 the first Sunday in April at 2:00am, and ends on the last Sunday in October
1998 EST+5EDT,M4.1.0/2,M10.5.0/2
2001 The schedule of Daylight Saving Time in any particular jurisdiction has
2002 changed over the years. To be strictly correct, the conversion of dates
2003 and times in the past should be based on the schedule that was in effect
2004 then. However, this format has no facilities to let you specify how the
2005 schedule has changed from year to year. The most you can do is specify
2006 one particular schedule---usually the present day schedule---and this is
2007 used to convert any date, no matter when. For precise time zone
2008 specifications, it is best to use the time zone information database
2011 The third format looks like this:
2017 Each operating system interprets this format differently; in the GNU C
2018 library, @var{characters} is the name of a file which describes the time
2021 @pindex /etc/localtime
2023 If the @code{TZ} environment variable does not have a value, the
2024 operation chooses a time zone by default. In the GNU C library, the
2025 default time zone is like the specification @samp{TZ=:/etc/localtime}
2026 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how GNU C library
2027 was configured; @pxref{Installation}). Other C libraries use their own
2028 rule for choosing the default time zone, so there is little we can say
2031 @cindex time zone database
2032 @pindex /share/lib/zoneinfo
2034 If @var{characters} begins with a slash, it is an absolute file name;
2035 otherwise the library looks for the file
2036 @w{@file{/share/lib/zoneinfo/@var{characters}}}. The @file{zoneinfo}
2037 directory contains data files describing local time zones in many
2038 different parts of the world. The names represent major cities, with
2039 subdirectories for geographical areas; for example,
2040 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
2041 These data files are installed by the system administrator, who also
2042 sets @file{/etc/localtime} to point to the data file for the local time
2043 zone. The GNU C library comes with a large database of time zone
2044 information for most regions of the world, which is maintained by a
2045 community of volunteers and put in the public domain.
2047 @node Time Zone Functions
2048 @subsection Functions and Variables for Time Zones
2052 @deftypevar {char *} tzname [2]
2053 The array @code{tzname} contains two strings, which are the standard
2054 names of the pair of time zones (standard and Daylight
2055 Saving) that the user has selected. @code{tzname[0]} is the name of
2056 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
2057 is the name for the time zone when Daylight Saving Time is in use (for
2058 example, @code{"EDT"}). These correspond to the @var{std} and @var{dst}
2059 strings (respectively) from the @code{TZ} environment variable. If
2060 Daylight Saving Time is never used, @code{tzname[1]} is the empty string.
2062 The @code{tzname} array is initialized from the @code{TZ} environment
2063 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
2064 @code{mktime}, or @code{localtime} is called. If multiple abbreviations
2065 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
2066 Time and Eastern Daylight Time), the array contains the most recent
2069 The @code{tzname} array is required for POSIX.1 compatibility, but in
2070 GNU programs it is better to use the @code{tm_zone} member of the
2071 broken-down time structure, since @code{tm_zone} reports the correct
2072 abbreviation even when it is not the latest one.
2074 Though the strings are declared as @code{char *} the user must refrain
2075 from modifying these strings. Modifying the strings will almost certainly
2082 @deftypefun void tzset (void)
2083 The @code{tzset} function initializes the @code{tzname} variable from
2084 the value of the @code{TZ} environment variable. It is not usually
2085 necessary for your program to call this function, because it is called
2086 automatically when you use the other time conversion functions that
2087 depend on the time zone.
2090 The following variables are defined for compatibility with System V
2091 Unix. Like @code{tzname}, these variables are set by calling
2092 @code{tzset} or the other time conversion functions.
2096 @deftypevar {long int} timezone
2097 This contains the difference between UTC and the latest local standard
2098 time, in seconds west of UTC. For example, in the U.S. Eastern time
2099 zone, the value is @code{5*60*60}. Unlike the @code{tm_gmtoff} member
2100 of the broken-down time structure, this value is not adjusted for
2101 daylight saving, and its sign is reversed. In GNU programs it is better
2102 to use @code{tm_gmtoff}, since it contains the correct offset even when
2103 it is not the latest one.
2108 @deftypevar int daylight
2109 This variable has a nonzero value if Daylight Saving Time rules apply.
2110 A nonzero value does not necessarily mean that Daylight Saving Time is
2111 now in effect; it means only that Daylight Saving Time is sometimes in
2115 @node Time Functions Example
2116 @subsection Time Functions Example
2118 Here is an example program showing the use of some of the calendar time
2122 @include strftim.c.texi
2125 It produces output like this:
2128 Wed Jul 31 13:02:36 1991
2129 Today is Wednesday, July 31.
2130 The time is 01:02 PM.
2134 @node Setting an Alarm
2135 @section Setting an Alarm
2137 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
2138 process to interrupt itself at some future time. They do this by setting a
2139 timer; when the timer expires, the process receives a signal.
2141 @cindex setting an alarm
2142 @cindex interval timer, setting
2143 @cindex alarms, setting
2144 @cindex timers, setting
2145 Each process has three independent interval timers available:
2149 A real-time timer that counts clock time. This timer sends a
2150 @code{SIGALRM} signal to the process when it expires.
2151 @cindex real-time timer
2152 @cindex timer, real-time
2155 A virtual timer that counts CPU time used by the process. This timer
2156 sends a @code{SIGVTALRM} signal to the process when it expires.
2157 @cindex virtual timer
2158 @cindex timer, virtual
2161 A profiling timer that counts both CPU time used by the process, and CPU
2162 time spent in system calls on behalf of the process. This timer sends a
2163 @code{SIGPROF} signal to the process when it expires.
2164 @cindex profiling timer
2165 @cindex timer, profiling
2167 This timer is useful for profiling in interpreters. The interval timer
2168 mechanism does not have the fine granularity necessary for profiling
2170 @c @xref{profil} !!!
2173 You can only have one timer of each kind set at any given time. If you
2174 set a timer that has not yet expired, that timer is simply reset to the
2177 You should establish a handler for the appropriate alarm signal using
2178 @code{signal} or @code{sigaction} before issuing a call to
2179 @code{setitimer} or @code{alarm}. Otherwise, an unusual chain of events
2180 could cause the timer to expire before your program establishes the
2181 handler. In this case it would be terminated, since termination is the
2182 default action for the alarm signals. @xref{Signal Handling}.
2184 The @code{setitimer} function is the primary means for setting an alarm.
2185 This facility is declared in the header file @file{sys/time.h}. The
2186 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
2187 simpler interface for setting the real-time timer.
2193 @deftp {Data Type} {struct itimerval}
2194 This structure is used to specify when a timer should expire. It contains
2195 the following members:
2197 @item struct timeval it_interval
2198 This is the interval between successive timer interrupts. If zero, the
2199 alarm will only be sent once.
2201 @item struct timeval it_value
2202 This is the interval to the first timer interrupt. If zero, the alarm is
2206 The @code{struct timeval} data type is described in @ref{High-Resolution
2212 @deftypefun int setitimer (int @var{which}, struct itimerval *@var{new}, struct itimerval *@var{old})
2213 The @code{setitimer} function sets the timer specified by @var{which}
2214 according to @var{new}. The @var{which} argument can have a value of
2215 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
2217 If @var{old} is not a null pointer, @code{setitimer} returns information
2218 about any previous unexpired timer of the same kind in the structure it
2221 The return value is @code{0} on success and @code{-1} on failure. The
2222 following @code{errno} error conditions are defined for this function:
2226 The timer interval was too large.
2232 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
2233 The @code{getitimer} function stores information about the timer specified
2234 by @var{which} in the structure pointed at by @var{old}.
2236 The return value and error conditions are the same as for @code{setitimer}.
2244 This constant can be used as the @var{which} argument to the
2245 @code{setitimer} and @code{getitimer} functions to specify the real-time
2250 @item ITIMER_VIRTUAL
2251 @findex ITIMER_VIRTUAL
2252 This constant can be used as the @var{which} argument to the
2253 @code{setitimer} and @code{getitimer} functions to specify the virtual
2260 This constant can be used as the @var{which} argument to the
2261 @code{setitimer} and @code{getitimer} functions to specify the profiling
2267 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
2268 The @code{alarm} function sets the real-time timer to expire in
2269 @var{seconds} seconds. If you want to cancel any existing alarm, you
2270 can do this by calling @code{alarm} with a @var{seconds} argument of
2273 The return value indicates how many seconds remain before the previous
2274 alarm would have been sent. If there is no previous alarm, @code{alarm}
2278 The @code{alarm} function could be defined in terms of @code{setitimer}
2283 alarm (unsigned int seconds)
2285 struct itimerval old, new;
2286 new.it_interval.tv_usec = 0;
2287 new.it_interval.tv_sec = 0;
2288 new.it_value.tv_usec = 0;
2289 new.it_value.tv_sec = (long int) seconds;
2290 if (setitimer (ITIMER_REAL, &new, &old) < 0)
2293 return old.it_value.tv_sec;
2297 There is an example showing the use of the @code{alarm} function in
2298 @ref{Handler Returns}.
2300 If you simply want your process to wait for a given number of seconds,
2301 you should use the @code{sleep} function. @xref{Sleeping}.
2303 You shouldn't count on the signal arriving precisely when the timer
2304 expires. In a multiprocessing environment there is typically some
2305 amount of delay involved.
2307 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
2308 functions are derived from BSD Unix, while the @code{alarm} function is
2309 specified by the POSIX.1 standard. @code{setitimer} is more powerful than
2310 @code{alarm}, but @code{alarm} is more widely used.
2315 The function @code{sleep} gives a simple way to make the program wait
2316 for short periods of time. If your program doesn't use signals (except
2317 to terminate), then you can expect @code{sleep} to wait reliably for
2318 the specified amount of time. Otherwise, @code{sleep} can return sooner
2319 if a signal arrives; if you want to wait for a given period regardless
2320 of signals, use @code{select} (@pxref{Waiting for I/O}) and don't
2321 specify any descriptors to wait for.
2322 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
2326 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
2327 The @code{sleep} function waits for @var{seconds} or until a signal
2328 is delivered, whichever happens first.
2330 If @code{sleep} function returns because the requested time has
2331 elapsed, it returns a value of zero. If it returns because of delivery
2332 of a signal, its return value is the remaining time in the sleep period.
2334 The @code{sleep} function is declared in @file{unistd.h}.
2337 Resist the temptation to implement a sleep for a fixed amount of time by
2338 using the return value of @code{sleep}, when nonzero, to call
2339 @code{sleep} again. This will work with a certain amount of accuracy as
2340 long as signals arrive infrequently. But each signal can cause the
2341 eventual wakeup time to be off by an additional second or so. Suppose a
2342 few signals happen to arrive in rapid succession by bad luck---there is
2343 no limit on how much this could shorten or lengthen the wait.
2345 Instead, compute the time at which the program should stop waiting, and
2346 keep trying to wait until that time. This won't be off by more than a
2347 second. With just a little more work, you can use @code{select} and
2348 make the waiting period quite accurate. (Of course, heavy system load
2349 can cause additional unavoidable delays---unless the machine is
2350 dedicated to one application, there is no way you can avoid this.)
2352 On some systems, @code{sleep} can do strange things if your program uses
2353 @code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being
2354 ignored or blocked when @code{sleep} is called, @code{sleep} might
2355 return prematurely on delivery of a @code{SIGALRM} signal. If you have
2356 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
2357 signal is delivered while the process is sleeping, the action taken
2358 might be just to cause @code{sleep} to return instead of invoking your
2359 handler. And, if @code{sleep} is interrupted by delivery of a signal
2360 whose handler requests an alarm or alters the handling of @code{SIGALRM},
2361 this handler and @code{sleep} will interfere.
2363 On the GNU system, it is safe to use @code{sleep} and @code{SIGALRM} in
2364 the same program, because @code{sleep} does not work by means of
2369 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
2370 If resolution to seconds is not enough the @code{nanosleep} function
2371 can be used. As the name suggests the sleeping period can be specified
2372 in nanoseconds. The actual period of waiting time might be longer since
2373 the requested time in the @var{requested_time} parameter is rounded up
2374 to the next integer multiple of the actual resolution of the system.
2376 If the function returns because the time has elapsed the return value is
2377 zero. If the function returns @math{-1} the global variable @var{errno}
2378 is set to the following values:
2382 The call was interrupted because a signal was delivered to the thread.
2383 If the @var{remaining} parameter is not the null pointer the structure
2384 pointed to by @var{remaining} is updated to contain the remaining time.
2387 The nanosecond value in the @var{requested_time} parameter contains an
2388 illegal value. Either the value is negative or greater than or equal to
2392 This function is a cancellation point in multi-threaded programs. This
2393 is a problem if the thread allocates some resources (like memory, file
2394 descriptors, semaphores or whatever) at the time @code{nanosleep} is
2395 called. If the thread gets canceled these resources stay allocated
2396 until the program ends. To avoid this calls to @code{nanosleep} should
2397 be protected using cancellation handlers.
2398 @c ref pthread_cleanup_push / pthread_cleanup_pop
2400 The @code{nanosleep} function is declared in @file{time.h}.