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