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