(_ISwbit): Protext use of parameter with parentheses.
[glibc.git] / manual / time.texi
blob46a2832326d0e841068933f33f6b89610124072a
1 @node Date and Time, Non-Local Exits, Arithmetic, Top
2 @c %MENU% Functions for getting the date and time and formatting them nicely
3 @chapter Date and Time
5 This chapter describes functions for manipulating dates and times,
6 including functions for determining what the current time is and
7 conversion between different time representations.
9 The time functions fall into three main categories:
11 @itemize @bullet
12 @item
13 Functions for measuring elapsed CPU time are discussed in @ref{Processor
14 Time}.
16 @item
17 Functions for measuring absolute clock or calendar time are discussed in
18 @ref{Calendar Time}.
20 @item
21 Functions for setting alarms and timers are discussed in @ref{Setting
22 an Alarm}.
23 @end itemize
25 @menu
26 * Processor Time::              Measures processor time used by a program.
27 * Calendar Time::               Manipulation of ``real'' dates and times.
28 * Setting an Alarm::            Sending a signal after a specified time.
29 * Sleeping::                    Waiting for a period of time.
30 * Resource Usage::              Measuring various resources used.
31 * Limits on Resources::         Specifying limits on resource usage.
32 * Priority::                    Reading or setting process run priority.
33 @end menu
35 @node Processor Time
36 @section Processor Time
38 If you're trying to optimize your program or measure its efficiency, it's
39 very useful to be able to know how much @dfn{processor time} or @dfn{CPU
40 time} it has used at any given point.  Processor time is different from
41 actual wall clock time because it doesn't include any time spent waiting
42 for I/O or when some other process is running.  Processor time is
43 represented by the data type @code{clock_t}, and is given as a number of
44 @dfn{clock ticks} relative to an arbitrary base time marking the beginning
45 of a single program invocation.
46 @cindex CPU time
47 @cindex processor time
48 @cindex clock ticks
49 @cindex ticks, clock
50 @cindex time, elapsed CPU
52 @menu
53 * Basic CPU Time::              The @code{clock} function.
54 * Detailed CPU Time::           The @code{times} function.
55 @end menu
57 @node Basic CPU Time
58 @subsection Basic CPU Time Inquiry
60 To get the elapsed CPU time used by a process, you can use the
61 @code{clock} function.  This facility is declared in the header file
62 @file{time.h}.
63 @pindex time.h
65 In typical usage, you call the @code{clock} function at the beginning and
66 end of the interval you want to time, subtract the values, and then divide
67 by @code{CLOCKS_PER_SEC} (the number of clock ticks per second), like this:
69 @smallexample
70 @group
71 #include <time.h>
73 clock_t start, end;
74 double elapsed;
76 start = clock();
77 @dots{} /* @r{Do the work.} */
78 end = clock();
79 elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
80 @end group
81 @end smallexample
83 Different computers and operating systems vary wildly in how they keep
84 track of processor time.  It's common for the internal processor clock
85 to have a resolution somewhere between hundredths and millionths of a
86 second.
88 In the GNU system, @code{clock_t} is equivalent to @code{long int} and
89 @code{CLOCKS_PER_SEC} is an integer value.  But in other systems, both
90 @code{clock_t} and the type of the macro @code{CLOCKS_PER_SEC} can be
91 either integer or floating-point types.  Casting processor time values
92 to @code{double}, as in the example above, makes sure that operations
93 such as arithmetic and printing work properly and consistently no matter
94 what the underlying representation is.
96 @comment time.h
97 @comment ISO
98 @deftypevr Macro int CLOCKS_PER_SEC
99 The value of this macro is the number of clock ticks per second measured
100 by the @code{clock} function.
101 @end deftypevr
103 @comment time.h
104 @comment POSIX.1
105 @deftypevr Macro int CLK_TCK
106 This is an obsolete name for @code{CLOCKS_PER_SEC}.
107 @end deftypevr
109 @comment time.h
110 @comment ISO
111 @deftp {Data Type} clock_t
112 This is the type of the value returned by the @code{clock} function.
113 Values of type @code{clock_t} are in units of clock ticks.
114 @end deftp
116 @comment time.h
117 @comment ISO
118 @deftypefun clock_t clock (void)
119 This function returns the elapsed processor time.  The base time is
120 arbitrary but doesn't change within a single process.  If the processor
121 time is not available or cannot be represented, @code{clock} returns the
122 value @code{(clock_t)(-1)}.
123 @end deftypefun
126 @node Detailed CPU Time
127 @subsection Detailed Elapsed CPU Time Inquiry
129 The @code{times} function returns more detailed information about
130 elapsed processor time in a @w{@code{struct tms}} object.  You should
131 include the header file @file{sys/times.h} to use this facility.
132 @pindex sys/times.h
134 @comment sys/times.h
135 @comment POSIX.1
136 @deftp {Data Type} {struct tms}
137 The @code{tms} structure is used to return information about process
138 times.  It contains at least the following members:
140 @table @code
141 @item clock_t tms_utime
142 This is the CPU time used in executing the instructions of the calling
143 process.
145 @item clock_t tms_stime
146 This is the CPU time used by the system on behalf of the calling process.
148 @item clock_t tms_cutime
149 This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
150 values of all terminated child processes of the calling process, whose
151 status has been reported to the parent process by @code{wait} or
152 @code{waitpid}; see @ref{Process Completion}.  In other words, it
153 represents the total CPU time used in executing the instructions of all
154 the terminated child processes of the calling process, excluding child
155 processes which have not yet been reported by @code{wait} or
156 @code{waitpid}.
158 @item clock_t tms_cstime
159 This is similar to @code{tms_cutime}, but represents the total CPU time
160 used by the system on behalf of all the terminated child processes of the
161 calling process.
162 @end table
164 All of the times are given in clock ticks.  These are absolute values; in a
165 newly created process, they are all zero.  @xref{Creating a Process}.
166 @end deftp
168 @comment sys/times.h
169 @comment POSIX.1
170 @deftypefun clock_t times (struct tms *@var{buffer})
171 The @code{times} function stores the processor time information for
172 the calling process in @var{buffer}.
174 The return value is the same as the value of @code{clock()}: the elapsed
175 real time relative to an arbitrary base.  The base is a constant within a
176 particular process, and typically represents the time since system
177 start-up.  A value of @code{(clock_t)(-1)} is returned to indicate failure.
178 @end deftypefun
180 @strong{Portability Note:} The @code{clock} function described in
181 @ref{Basic CPU Time}, is specified by the @w{ISO C} standard.  The
182 @code{times} function is a feature of POSIX.1.  In the GNU system, the
183 value returned by the @code{clock} function is equivalent to the sum of
184 the @code{tms_utime} and @code{tms_stime} fields returned by
185 @code{times}.
187 @node Calendar Time
188 @section Calendar Time
190 This section describes facilities for keeping track of dates and times
191 according to the Gregorian calendar.
192 @cindex Gregorian calendar
193 @cindex time, calendar
194 @cindex date and time
196 There are three representations for date and time information:
198 @itemize @bullet
199 @item
200 @dfn{Calendar time} (the @code{time_t} data type) is a compact
201 representation, typically giving the number of seconds elapsed since
202 some implementation-specific base time.
203 @cindex calendar time
205 @item
206 There is also a @dfn{high-resolution time} representation (the @code{struct
207 timeval} data type) that includes fractions of a second.  Use this time
208 representation instead of ordinary calendar time when you need greater
209 precision.
210 @cindex high-resolution time
212 @item
213 @dfn{Local time} or @dfn{broken-down time} (the @code{struct
214 tm} data type) represents the date and time as a set of components
215 specifying the year, month, and so on, for a specific time zone.
216 This time representation is usually used in conjunction with formatting
217 date and time values.
218 @cindex local time
219 @cindex broken-down time
220 @end itemize
222 @menu
223 * Simple Calendar Time::        Facilities for manipulating calendar time.
224 * High-Resolution Calendar::    A time representation with greater precision.
225 * Broken-down Time::            Facilities for manipulating local time.
226 * Formatting Date and Time::    Converting times to strings.
227 * TZ Variable::                 How users specify the time zone.
228 * Time Zone Functions::         Functions to examine or specify the time zone.
229 * Time Functions Example::      An example program showing use of some of
230                                  the time functions.
231 @end menu
233 @node Simple Calendar Time
234 @subsection Simple Calendar Time
236 This section describes the @code{time_t} data type for representing
237 calendar time, and the functions which operate on calendar time objects.
238 These facilities are declared in the header file @file{time.h}.
239 @pindex time.h
241 @cindex epoch
242 @comment time.h
243 @comment ISO
244 @deftp {Data Type} time_t
245 This is the data type used to represent calendar time.
246 When interpreted as an absolute time
247 value, it represents the number of seconds elapsed since 00:00:00 on
248 January 1, 1970, Coordinated Universal Time.  (This date is sometimes
249 referred to as the @dfn{epoch}.)  POSIX requires that this count
250 ignore leap seconds, but on some hosts this count includes leap seconds
251 if you set @code{TZ} to certain values (@pxref{TZ Variable}).
253 In the GNU C library, @code{time_t} is equivalent to @code{long int}.
254 In other systems, @code{time_t} might be either an integer or
255 floating-point type.
256 @end deftp
258 @comment time.h
259 @comment ISO
260 @deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
261 The @code{difftime} function returns the number of seconds elapsed
262 between time @var{time1} and time @var{time0}, as a value of type
263 @code{double}.  The difference ignores leap seconds unless leap
264 second support is enabled.
266 In the GNU system, you can simply subtract @code{time_t} values.  But on
267 other systems, the @code{time_t} data type might use some other encoding
268 where subtraction doesn't work directly.
269 @end deftypefun
271 @comment time.h
272 @comment ISO
273 @deftypefun time_t time (time_t *@var{result})
274 The @code{time} function returns the current time as a value of type
275 @code{time_t}.  If the argument @var{result} is not a null pointer, the
276 time value is also stored in @code{*@var{result}}.  If the calendar
277 time is not available, the value @w{@code{(time_t)(-1)}} is returned.
278 @end deftypefun
281 @node High-Resolution Calendar
282 @subsection High-Resolution Calendar
284 The @code{time_t} data type used to represent calendar times has a
285 resolution of only one second.  Some applications need more precision.
287 So, the GNU C library also contains functions which are capable of
288 representing calendar times to a higher resolution than one second.  The
289 functions and the associated data types described in this section are
290 declared in @file{sys/time.h}.
291 @pindex sys/time.h
293 @comment sys/time.h
294 @comment BSD
295 @deftp {Data Type} {struct timeval}
296 The @code{struct timeval} structure represents a calendar time.  It
297 has the following members:
299 @table @code
300 @item long int tv_sec
301 This represents the number of seconds since the epoch.  It is equivalent
302 to a normal @code{time_t} value.
304 @item long int tv_usec
305 This is the fractional second value, represented as the number of
306 microseconds.
308 Some times struct timeval values are used for time intervals.  Then the
309 @code{tv_sec} member is the number of seconds in the interval, and
310 @code{tv_usec} is the number of additional microseconds.
311 @end table
312 @end deftp
314 @comment sys/time.h
315 @comment BSD
316 @deftp {Data Type} {struct timezone}
317 The @code{struct timezone} structure is used to hold minimal information
318 about the local time zone.  It has the following members:
320 @table @code
321 @item int tz_minuteswest
322 This is the number of minutes west of UTC.
324 @item int tz_dsttime
325 If nonzero, daylight saving time applies during some part of the year.
326 @end table
328 The @code{struct timezone} type is obsolete and should never be used.
329 Instead, use the facilities described in @ref{Time Zone Functions}.
330 @end deftp
332 It is often necessary to subtract two values of type @w{@code{struct
333 timeval}}.  Here is the best way to do this.  It works even on some
334 peculiar operating systems where the @code{tv_sec} member has an
335 unsigned type.
337 @smallexample
338 /* @r{Subtract the `struct timeval' values X and Y,}
339    @r{storing the result in RESULT.}
340    @r{Return 1 if the difference is negative, otherwise 0.}  */
343 timeval_subtract (result, x, y)
344      struct timeval *result, *x, *y;
346   /* @r{Perform the carry for the later subtraction by updating @var{y}.} */
347   if (x->tv_usec < y->tv_usec) @{
348     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
349     y->tv_usec -= 1000000 * nsec;
350     y->tv_sec += nsec;
351   @}
352   if (x->tv_usec - y->tv_usec > 1000000) @{
353     int nsec = (y->tv_usec - x->tv_usec) / 1000000;
354     y->tv_usec += 1000000 * nsec;
355     y->tv_sec -= nsec;
356   @}
358   /* @r{Compute the time remaining to wait.}
359      @r{@code{tv_usec} is certainly positive.} */
360   result->tv_sec = x->tv_sec - y->tv_sec;
361   result->tv_usec = x->tv_usec - y->tv_usec;
363   /* @r{Return 1 if result is negative.} */
364   return x->tv_sec < y->tv_sec;
366 @end smallexample
368 @comment sys/time.h
369 @comment BSD
370 @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
371 The @code{gettimeofday} function returns the current date and time in the
372 @code{struct timeval} structure indicated by @var{tp}.  Information about the
373 time zone is returned in the structure pointed at @var{tzp}.  If the @var{tzp}
374 argument is a null pointer, time zone information is ignored.
376 The return value is @code{0} on success and @code{-1} on failure.  The
377 following @code{errno} error condition is defined for this function:
379 @table @code
380 @item ENOSYS
381 The operating system does not support getting time zone information, and
382 @var{tzp} is not a null pointer.  The GNU operating system does not
383 support using @w{@code{struct timezone}} to represent time zone
384 information; that is an obsolete feature of 4.3 BSD.
385 Instead, use the facilities described in @ref{Time Zone Functions}.
386 @end table
387 @end deftypefun
389 @comment sys/time.h
390 @comment BSD
391 @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
392 The @code{settimeofday} function sets the current date and time
393 according to the arguments.  As for @code{gettimeofday}, time zone
394 information is ignored if @var{tzp} is a null pointer.
396 You must be a privileged user in order to use @code{settimeofday}.
398 The return value is @code{0} on success and @code{-1} on failure.  The
399 following @code{errno} error conditions are defined for this function:
401 @table @code
402 @item EPERM
403 This process cannot set the time because it is not privileged.
405 @item ENOSYS
406 The operating system does not support setting time zone information, and
407 @var{tzp} is not a null pointer.
408 @end table
409 @end deftypefun
411 @comment sys/time.h
412 @comment BSD
413 @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
414 This function speeds up or slows down the system clock in order to make
415 gradual adjustments in the current time.  This ensures that the time
416 reported by the system clock is always monotonically increasing, which
417 might not happen if you simply set the current time.
419 The @var{delta} argument specifies a relative adjustment to be made to
420 the current time.  If negative, the system clock is slowed down for a
421 while until it has lost this much time.  If positive, the system clock
422 is speeded up for a while.
424 If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
425 function returns information about any previous time adjustment that
426 has not yet completed.
428 This function is typically used to synchronize the clocks of computers
429 in a local network.  You must be a privileged user to use it.
430 The return value is @code{0} on success and @code{-1} on failure.  The
431 following @code{errno} error condition is defined for this function:
433 @table @code
434 @item EPERM
435 You do not have privilege to set the time.
436 @end table
437 @end deftypefun
439 @strong{Portability Note:}  The @code{gettimeofday}, @code{settimeofday},
440 and @code{adjtime} functions are derived from BSD.
443 @node Broken-down Time
444 @subsection Broken-down Time
445 @cindex broken-down time
446 @cindex calendar time and broken-down time
448 Calendar time is represented as a number of seconds.  This is convenient
449 for calculation, but has no resemblance to the way people normally
450 represent dates and times.  By contrast, @dfn{broken-down time} is a binary
451 representation separated into year, month, day, and so on.  Broken down
452 time values are not useful for calculations, but they are useful for
453 printing human readable time.
455 A broken-down time value is always relative to a choice of local time
456 zone, and it also indicates which time zone was used.
458 The symbols in this section are declared in the header file @file{time.h}.
460 @comment time.h
461 @comment ISO
462 @deftp {Data Type} {struct tm}
463 This is the data type used to represent a broken-down time.  The structure
464 contains at least the following members, which can appear in any order:
466 @table @code
467 @item int tm_sec
468 This is the number of seconds after the minute, normally in the range
469 @code{0} through @code{59}.  (The actual upper limit is @code{60}, to allow
470 for leap seconds if leap second support is available.)
471 @cindex leap second
473 @item int tm_min
474 This is the number of minutes after the hour, in the range @code{0} through
475 @code{59}.
477 @item int tm_hour
478 This is the number of hours past midnight, in the range @code{0} through
479 @code{23}.
481 @item int tm_mday
482 This is the day of the month, in the range @code{1} through @code{31}.
484 @item int tm_mon
485 This is the number of months since January, in the range @code{0} through
486 @code{11}.
488 @item int tm_year
489 This is the number of years since @code{1900}.
491 @item int tm_wday
492 This is the number of days since Sunday, in the range @code{0} through
493 @code{6}.
495 @item int tm_yday
496 This is the number of days since January 1, in the range @code{0} through
497 @code{365}.
499 @item int tm_isdst
500 @cindex Daylight Saving Time
501 @cindex summer time
502 This is a flag that indicates whether Daylight Saving Time is (or was, or
503 will be) in effect at the time described.  The value is positive if
504 Daylight Saving Time is in effect, zero if it is not, and negative if the
505 information is not available.
507 @item long int tm_gmtoff
508 This field describes the time zone that was used to compute this
509 broken-down time value, including any adjustment for daylight saving; it
510 is the number of seconds that you must add to UTC to get local time.
511 You can also think of this as the number of seconds east of UTC.  For
512 example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
513 The @code{tm_gmtoff} field is derived from BSD and is a GNU library
514 extension; it is not visible in a strict @w{ISO C} environment.
516 @item const char *tm_zone
517 This field is the name for the time zone that was used to compute this
518 broken-down time value.  Like @code{tm_gmtoff}, this field is a BSD and
519 GNU extension, and is not visible in a strict @w{ISO C} environment.
520 @end table
521 @end deftp
523 @comment time.h
524 @comment ISO
525 @deftypefun {struct tm *} localtime (const time_t *@var{time})
526 The @code{localtime} function converts the calendar time pointed to by
527 @var{time} to broken-down time representation, expressed relative to the
528 user's specified time zone.
530 The return value is a pointer to a static broken-down time structure, which
531 might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
532 or @code{localtime}.  (But no other library function overwrites the contents
533 of this object.)
535 The return value is the null pointer if @var{time} cannot be represented
536 as a broken-down time; typically this is because the year cannot fit into
537 an @code{int}.
539 Calling @code{localtime} has one other effect: it sets the variable
540 @code{tzname} with information about the current time zone.  @xref{Time
541 Zone Functions}.
542 @end deftypefun
544 Using the @code{localtime} function is a big problem in multi-threaded
545 programs.  The result is returned in a static buffer and this is used in
546 all threads.  POSIX.1c introduced a varient of this function.
548 @comment time.h
549 @comment POSIX.1c
550 @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
551 The @code{localtime_r} function works just like the @code{localtime}
552 function.  It takes a pointer to a variable containing the calendar time
553 and converts it to the broken-down time format.
555 But the result is not placed in a static buffer.  Instead it is placed
556 in the object of type @code{struct tm} to which the parameter
557 @var{resultp} points.
559 If the conversion is successful the function returns a pointer to the
560 object the result was written into, i.e., it returns @var{resultp}.
561 @end deftypefun
564 @comment time.h
565 @comment ISO
566 @deftypefun {struct tm *} gmtime (const time_t *@var{time})
567 This function is similar to @code{localtime}, except that the broken-down
568 time is expressed as Coordinated Universal Time (UTC)---that is, as
569 Greenwich Mean Time (GMT)---rather than relative to the local time zone.
571 Recall that calendar times are @emph{always} expressed in coordinated
572 universal time.
573 @end deftypefun
575 As for the @code{localtime} function we have the problem that the result
576 is placed in a static variable.  POSIX.1c also provides a replacement for
577 @code{gmtime}.
579 @comment time.h
580 @comment POSIX.1c
581 @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
582 This function is similar to @code{localtime_r}, except that it converts
583 just like @code{gmtime} the given time as Coordinated Universal Time.
585 If the conversion is successful the function returns a pointer to the
586 object the result was written into, i.e., it returns @var{resultp}.
587 @end deftypefun
590 @comment time.h
591 @comment ISO
592 @deftypefun time_t mktime (struct tm *@var{brokentime})
593 The @code{mktime} function is used to convert a broken-down time structure
594 to a calendar time representation.  It also ``normalizes'' the contents of
595 the broken-down time structure, by filling in the day of week and day of
596 year based on the other date and time components.
598 The @code{mktime} function ignores the specified contents of the
599 @code{tm_wday} and @code{tm_yday} members of the broken-down time
600 structure.  It uses the values of the other components to compute the
601 calendar time; it's permissible for these components to have
602 unnormalized values outside of their normal ranges.  The last thing that
603 @code{mktime} does is adjust the components of the @var{brokentime}
604 structure (including the @code{tm_wday} and @code{tm_yday}).
606 If the specified broken-down time cannot be represented as a calendar time,
607 @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
608 the contents of @var{brokentime}.
610 Calling @code{mktime} also sets the variable @code{tzname} with
611 information about the current time zone.  @xref{Time Zone Functions}.
612 @end deftypefun
614 @node Formatting Date and Time
615 @subsection Formatting Date and Time
617 The functions described in this section format time values as strings.
618 These functions are declared in the header file @file{time.h}.
619 @pindex time.h
621 @comment time.h
622 @comment ISO
623 @deftypefun {char *} asctime (const struct tm *@var{brokentime})
624 The @code{asctime} function converts the broken-down time value that
625 @var{brokentime} points to into a string in a standard format:
627 @smallexample
628 "Tue May 21 13:46:22 1991\n"
629 @end smallexample
631 The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
632 @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
634 The abbreviations for the months are: @samp{Jan}, @samp{Feb},
635 @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
636 @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
638 The return value points to a statically allocated string, which might be
639 overwritten by subsequent calls to @code{asctime} or @code{ctime}.
640 (But no other library function overwrites the contents of this
641 string.)
642 @end deftypefun
644 @comment time.h
645 @comment POSIX.1c
646 @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
647 This function is similar to @code{asctime} but instead of placing the
648 result in a static buffer it writes the string in the buffer pointed to
649 by the parameter @var{buffer}.  This buffer should have at least room
650 for 16 bytes.
652 If no error occurred the function returns a pointer to the string the
653 result was written into, i.e., it returns @var{buffer}.  Otherwise
654 return @code{NULL}.
655 @end deftypefun
658 @comment time.h
659 @comment ISO
660 @deftypefun {char *} ctime (const time_t *@var{time})
661 The @code{ctime} function is similar to @code{asctime}, except that the
662 time value is specified as a @code{time_t} calendar time value rather
663 than in broken-down local time format.  It is equivalent to
665 @smallexample
666 asctime (localtime (@var{time}))
667 @end smallexample
669 @code{ctime} sets the variable @code{tzname}, because @code{localtime}
670 does so.  @xref{Time Zone Functions}.
671 @end deftypefun
673 @comment time.h
674 @comment POSIX.1c
675 @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
676 This function is similar to @code{ctime}, only that it places the result
677 in the string pointed to by @var{buffer}.  It is equivalent to (written
678 using gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
680 @smallexample
681 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
682 @end smallexample
684 If no error occurred the function returns a pointer to the string the
685 result was written into, i.e., it returns @var{buffer}.  Otherwise
686 return @code{NULL}.
687 @end deftypefun
690 @comment time.h
691 @comment ISO
692 @comment POSIX.2
693 @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
694 This function is similar to the @code{sprintf} function (@pxref{Formatted
695 Input}), but the conversion specifications that can appear in the format
696 template @var{template} are specialized for printing components of the date
697 and time @var{brokentime} according to the locale currently specified for
698 time conversion (@pxref{Locales}).
700 Ordinary characters appearing in the @var{template} are copied to the
701 output string @var{s}; this can include multibyte character sequences.
702 Conversion specifiers are introduced by a @samp{%} character, followed
703 by an optional flag which can be one of the following.  These flags
704 are all GNU extensions. The first three affect only the output of
705 numbers:
707 @table @code
708 @item _
709 The number is padded with spaces.
711 @item -
712 The number is not padded at all.
714 @item 0
715 The number is padded with zeros even if the format specifies padding
716 with spaces.
718 @item ^
719 The output uses uppercase characters, but only if this is possible
720 (@pxref{Case Conversion}).
721 @end table
723 The default action is to pad the number with zeros to keep it a constant
724 width.  Numbers that do not have a range indicated below are never
725 padded, since there is no natural width for them.
727 Following the flag an optional specification of the width is possible.
728 This is specified in decimal notation.  If the natural size of the
729 output is of the field has less than the specified number of characters,
730 the result is written right adjusted and space padded to the given
731 size.
733 An optional modifier can follow the optional flag and width
734 specification.  The modifiers, which are POSIX.2 extensions, are:
736 @table @code
737 @item E
738 Use the locale's alternate representation for date and time.  This
739 modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
740 @code{%y} and @code{%Y} format specifiers.  In a Japanese locale, for
741 example, @code{%Ex} might yield a date format based on the Japanese
742 Emperors' reigns.
744 @item O
745 Use the locale's alternate numeric symbols for numbers.  This modifier
746 applies only to numeric format specifiers.
747 @end table
749 If the format supports the modifier but no alternate representation
750 is available, it is ignored.
752 The conversion specifier ends with a format specifier taken from the
753 following list.  The whole @samp{%} sequence is replaced in the output
754 string as follows:
756 @table @code
757 @item %a
758 The abbreviated weekday name according to the current locale.
760 @item %A
761 The full weekday name according to the current locale.
763 @item %b
764 The abbreviated month name according to the current locale.
766 @item %B
767 The full month name according to the current locale.
769 @item %c
770 The preferred date and time representation for the current locale.
772 @item %C
773 The century of the year.  This is equivalent to the greatest integer not
774 greater than the year divided by 100.
776 This format is a POSIX.2 extension.
778 @item %d
779 The day of the month as a decimal number (range @code{01} through @code{31}).
781 @item %D
782 The date using the format @code{%m/%d/%y}.
784 This format is a POSIX.2 extension.
786 @item %e
787 The day of the month like with @code{%d}, but padded with blank (range
788 @code{ 1} through @code{31}).
790 This format is a POSIX.2 extension.
792 @item %f
793 The day of the week as a decimal number (range @code{1} through
794 @code{7}), Monday being @code{1}.
796 This format is a @w{ISO C 9X} extension.
798 @item %F
799 The date using the format @code{%Y-%m-%d}.  This is the form specified
800 in the @w{ISO 8601} standard and is the preferred form for all uses.
802 This format is a @w{ISO C 9X} extension.
804 @item %g
805 The year corresponding to the ISO week number, but without the century
806 (range @code{00} through @code{99}).  This has the same format and value
807 as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
808 to the previous or next year, that year is used instead.
810 This format is a GNU extension.
812 @item %G
813 The year corresponding to the ISO week number.  This has the same format
814 and value as @code{%Y}, except that if the ISO week number (see
815 @code{%V}) belongs to the previous or next year, that year is used
816 instead.
818 This format is a GNU extension.
820 @item %h
821 The abbreviated month name according to the current locale.  The action
822 is the same as for @code{%b}.
824 This format is a POSIX.2 extension.
826 @item %H
827 The hour as a decimal number, using a 24-hour clock (range @code{00} through
828 @code{23}).
830 @item %I
831 The hour as a decimal number, using a 12-hour clock (range @code{01} through
832 @code{12}).
834 @item %j
835 The day of the year as a decimal number (range @code{001} through @code{366}).
837 @item %k
838 The hour as a decimal number, using a 24-hour clock like @code{%H}, but
839 padded with blank (range @code{ 0} through @code{23}).
841 This format is a GNU extension.
843 @item %l
844 The hour as a decimal number, using a 12-hour clock like @code{%I}, but
845 padded with blank (range @code{ 1} through @code{12}).
847 This format is a GNU extension.
849 @item %m
850 The month as a decimal number (range @code{01} through @code{12}).
852 @item %M
853 The minute as a decimal number (range @code{00} through @code{59}).
855 @item %n
856 A single @samp{\n} (newline) character.
858 This format is a POSIX.2 extension.
860 @item %p
861 Either @samp{AM} or @samp{PM}, according to the given time value; or the
862 corresponding strings for the current locale.  Noon is treated as
863 @samp{PM} and midnight as @samp{AM}.
865 @ignore
866 We currently have a problem with makeinfo.  Write @samp{AM} and @samp{am}
867 both results in `am'.  I.e., the difference in case is not visible anymore.
868 @end ignore
869 @item %P
870 Either @samp{am} or @samp{pm}, according to the given time value; or the
871 corresponding strings for the current locale, printed in lowercase
872 characters.  Noon is treated as @samp{pm} and midnight as @samp{am}.
874 This format is a GNU extension.
876 @item %r
877 The complete time using the AM/PM format of the current locale.
879 This format is a POSIX.2 extension.
881 @item %R
882 The hour and minute in decimal numbers using the format @code{%H:%M}.
884 This format is a GNU extension.
886 @item %s
887 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
888 Leap seconds are not counted unless leap second support is available.
890 This format is a GNU extension.
892 @item %S
893 The second as a decimal number (range @code{00} through @code{60}).
895 @item %t
896 A single @samp{\t} (tabulator) character.
898 This format is a POSIX.2 extension.
900 @item %T
901 The time using decimal numbers using the format @code{%H:%M:%S}.
903 This format is a POSIX.2 extension.
905 @item %u
906 The day of the week as a decimal number (range @code{1} through
907 @code{7}), Monday being @code{1}.
909 This format is a POSIX.2 extension.
911 @item %U
912 The week number of the current year as a decimal number (range @code{00}
913 through @code{53}), starting with the first Sunday as the first day of
914 the first week.  Days preceding the first Sunday in the year are
915 considered to be in week @code{00}.
917 @item %V
918 The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
919 through @code{53}).  ISO weeks start with Monday and end with Sunday.
920 Week @code{01} of a year is the first week which has the majority of its
921 days in that year; this is equivalent to the week containing the year's
922 first Thursday, and it is also equivalent to the week containing January
923 4.  Week @code{01} of a year can contain days from the previous year.
924 The week before week @code{01} of a year is the last week (@code{52} or
925 @code{53}) of the previous year even if it contains days from the new
926 year.
928 This format is a POSIX.2 extension.
930 @item %w
931 The day of the week as a decimal number (range @code{0} through
932 @code{6}), Sunday being @code{0}.
934 @item %W
935 The week number of the current year as a decimal number (range @code{00}
936 through @code{53}), starting with the first Monday as the first day of
937 the first week.  All days preceding the first Monday in the year are
938 considered to be in week @code{00}.
940 @item %x
941 The preferred date representation for the current locale, but without the
942 time.
944 @item %X
945 The preferred time representation for the current locale, but with no date.
947 @item %y
948 The year without a century as a decimal number (range @code{00} through
949 @code{99}).  This is equivalent to the year modulo 100.
951 @item %Y
952 The year as a decimal number, using the Gregorian calendar.  Years
953 before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
955 @item %z
956 @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
957 @code{-0600} or @code{+0100}), or nothing if no time zone is
958 determinable.
960 This format is a GNU extension.
962 A full @w{RFC 822} timestamp is generated by the format 
963 @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent 
964 @w{@samp{"%a, %d %b %Y %T %z"}}).
966 @item %Z
967 The time zone abbreviation (empty if the time zone can't be determined).
969 @item %%
970 A literal @samp{%} character.
971 @end table
973 The @var{size} parameter can be used to specify the maximum number of
974 characters to be stored in the array @var{s}, including the terminating
975 null character.  If the formatted time requires more than @var{size}
976 characters, @code{strftime} returns zero and the content of the array
977 @var{s} is indetermined.  Otherwise the return value indicates the
978 number of characters placed in the array @var{s}, not including the
979 terminating null character.
981 @emph{Warning:} This convention for the return value which is prescribed
982 in @w{ISO C} can lead to problems in some situations.  For certain
983 format strings and certain locales the output really can be the empty
984 string and this cannot be discovered by testing the return value only.
985 E.g., in most locales the AM/PM time format is not supported (most of
986 the world uses the 24 hour time representation).  In such locales
987 @code{"%p"} will return the empty string, i.e., the return value is
988 zero.  To detect situations like this something similar to the following
989 code should be used:
991 @smallexample
992 buf[0] = '\1';
993 len = strftime (buf, bufsize, format, tp);
994 if (len == 0 && buf[0] != '\0')
995   @{
996     /* Something went wrong in the strftime call.  */
997     @dots{}
998   @}
999 @end smallexample
1001 If @var{s} is a null pointer, @code{strftime} does not actually write
1002 anything, but instead returns the number of characters it would have written.
1004 According to POSIX.1 every call to @code{strftime} implies a call to
1005 @code{tzset}.  So the contents of the environment variable @code{TZ}
1006 is examined before any output is produced.
1008 For an example of @code{strftime}, see @ref{Time Functions Example}.
1009 @end deftypefun
1011 @node TZ Variable
1012 @subsection Specifying the Time Zone with @code{TZ}
1014 In POSIX systems, a user can specify the time zone by means of the
1015 @code{TZ} environment variable.  For information about how to set
1016 environment variables, see @ref{Environment Variables}.  The functions
1017 for accessing the time zone are declared in @file{time.h}.
1018 @pindex time.h
1019 @cindex time zone
1021 You should not normally need to set @code{TZ}.  If the system is
1022 configured properly, the default time zone will be correct.  You might
1023 set @code{TZ} if you are using a computer over the network from a
1024 different time zone, and would like times reported to you in the time zone
1025 that local for you, rather than what is local for the computer.
1027 In POSIX.1 systems the value of the @code{TZ} variable can be of one of
1028 three formats.  With the GNU C library, the most common format is the
1029 last one, which can specify a selection from a large database of time
1030 zone information for many regions of the world.  The first two formats
1031 are used to describe the time zone information directly, which is both
1032 more cumbersome and less precise.  But the POSIX.1 standard only
1033 specifies the details of the first two formats, so it is good to be
1034 familiar with them in case you come across a POSIX.1 system that doesn't
1035 support a time zone information database.
1037 The first format is used when there is no Daylight Saving Time (or
1038 summer time) in the local time zone:
1040 @smallexample
1041 @r{@var{std} @var{offset}}
1042 @end smallexample
1044 The @var{std} string specifies the name of the time zone.  It must be
1045 three or more characters long and must not contain a leading colon or
1046 embedded digits, commas, or plus or minus signs.  There is no space
1047 character separating the time zone name from the @var{offset}, so these
1048 restrictions are necessary to parse the specification correctly.
1050 The @var{offset} specifies the time value one must add to the local time
1051 to get a Coordinated Universal Time value.  It has syntax like
1052 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]].  This
1053 is positive if the local time zone is west of the Prime Meridian and
1054 negative if it is east.  The hour must be between @code{0} and
1055 @code{23}, and the minute and seconds between @code{0} and @code{59}.
1057 For example, here is how we would specify Eastern Standard Time, but
1058 without any daylight saving time alternative:
1060 @smallexample
1061 EST+5
1062 @end smallexample
1064 The second format is used when there is Daylight Saving Time:
1066 @smallexample
1067 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
1068 @end smallexample
1070 The initial @var{std} and @var{offset} specify the standard time zone, as
1071 described above.  The @var{dst} string and @var{offset} specify the name
1072 and offset for the corresponding daylight saving time zone; if the
1073 @var{offset} is omitted, it defaults to one hour ahead of standard time.
1075 The remainder of the specification describes when daylight saving time is
1076 in effect.  The @var{start} field is when daylight saving time goes into
1077 effect and the @var{end} field is when the change is made back to standard
1078 time.  The following formats are recognized for these fields:
1080 @table @code
1081 @item J@var{n}
1082 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
1083 February 29 is never counted, even in leap years.
1085 @item @var{n}
1086 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
1087 February 29 is counted in leap years.
1089 @item M@var{m}.@var{w}.@var{d}
1090 This specifies day @var{d} of week @var{w} of month @var{m}.  The day
1091 @var{d} must be between @code{0} (Sunday) and @code{6}.  The week
1092 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
1093 first week in which day @var{d} occurs, and week @code{5} specifies the
1094 @emph{last} @var{d} day in the month.  The month @var{m} should be
1095 between @code{1} and @code{12}.
1096 @end table
1098 The @var{time} fields specify when, in the local time currently in
1099 effect, the change to the other time occurs.  If omitted, the default is
1100 @code{02:00:00}.
1102 For example, here is how one would specify the Eastern time zone in the
1103 United States, including the appropriate daylight saving time and its dates
1104 of applicability.  The normal offset from UTC is 5 hours; since this is
1105 west of the prime meridian, the sign is positive.  Summer time begins on
1106 the first Sunday in April at 2:00am, and ends on the last Sunday in October
1107 at 2:00am.
1109 @smallexample
1110 EST+5EDT,M4.1.0/2,M10.5.0/2
1111 @end smallexample
1113 The schedule of daylight saving time in any particular jurisdiction has
1114 changed over the years.  To be strictly correct, the conversion of dates
1115 and times in the past should be based on the schedule that was in effect
1116 then.  However, this format has no facilities to let you specify how the
1117 schedule has changed from year to year.  The most you can do is specify
1118 one particular schedule---usually the present day schedule---and this is
1119 used to convert any date, no matter when.  For precise time zone
1120 specifications, it is best to use the time zone information database
1121 (see below).
1123 The third format looks like this:
1125 @smallexample
1126 :@var{characters}
1127 @end smallexample
1129 Each operating system interprets this format differently; in the GNU C
1130 library, @var{characters} is the name of a file which describes the time
1131 zone.
1133 @pindex /etc/localtime
1134 @pindex localtime
1135 If the @code{TZ} environment variable does not have a value, the
1136 operation chooses a time zone by default.  In the GNU C library, the
1137 default time zone is like the specification @samp{TZ=:/etc/localtime}
1138 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how GNU C library
1139 was configured; @pxref{Installation}).  Other C libraries use their own
1140 rule for choosing the default time zone, so there is little we can say
1141 about them.
1143 @cindex time zone database
1144 @pindex /share/lib/zoneinfo
1145 @pindex zoneinfo
1146 If @var{characters} begins with a slash, it is an absolute file name;
1147 otherwise the library looks for the file
1148 @w{@file{/share/lib/zoneinfo/@var{characters}}}.  The @file{zoneinfo}
1149 directory contains data files describing local time zones in many
1150 different parts of the world.  The names represent major cities, with
1151 subdirectories for geographical areas; for example,
1152 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
1153 These data files are installed by the system administrator, who also
1154 sets @file{/etc/localtime} to point to the data file for the local time
1155 zone.  The GNU C library comes with a large database of time zone
1156 information for most regions of the world, which is maintained by a
1157 community of volunteers and put in the public domain.
1159 @node Time Zone Functions
1160 @subsection Functions and Variables for Time Zones
1162 @comment time.h
1163 @comment POSIX.1
1164 @deftypevar {char *} tzname [2]
1165 The array @code{tzname} contains two strings, which are the standard
1166 names of the pair of time zones (standard and daylight
1167 saving) that the user has selected.  @code{tzname[0]} is the name of
1168 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
1169 is the name for the time zone when daylight saving time is in use (for
1170 example, @code{"EDT"}).  These correspond to the @var{std} and @var{dst}
1171 strings (respectively) from the @code{TZ} environment variable.  If
1172 daylight saving time is never used, @code{tzname[1]} is the empty string.
1174 The @code{tzname} array is initialized from the @code{TZ} environment
1175 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
1176 @code{mktime}, or @code{localtime} is called.  If multiple abbreviations
1177 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
1178 Time and Eastern Daylight Time), the array contains the most recent
1179 abbreviation.
1181 The @code{tzname} array is required for POSIX.1 compatibility, but in
1182 GNU programs it is better to use the @code{tm_zone} member of the
1183 broken-down time structure, since @code{tm_zone} reports the correct
1184 abbreviation even when it is not the latest one.
1186 Though the strings are declared as @code{char *} the user must stay away
1187 from modifying these strings.  Modifying the strings will almost certainly
1188 lead to trouble.
1190 @end deftypevar
1192 @comment time.h
1193 @comment POSIX.1
1194 @deftypefun void tzset (void)
1195 The @code{tzset} function initializes the @code{tzname} variable from
1196 the value of the @code{TZ} environment variable.  It is not usually
1197 necessary for your program to call this function, because it is called
1198 automatically when you use the other time conversion functions that
1199 depend on the time zone.
1200 @end deftypefun
1202 The following variables are defined for compatibility with System V
1203 Unix.  Like @code{tzname}, these variables are set by calling
1204 @code{tzset} or the other time conversion functions.
1206 @comment time.h
1207 @comment SVID
1208 @deftypevar {long int} timezone
1209 This contains the difference between UTC and the latest local standard
1210 time, in seconds west of UTC.  For example, in the U.S. Eastern time
1211 zone, the value is @code{5*60*60}.  Unlike the @code{tm_gmtoff} member
1212 of the broken-down time structure, this value is not adjusted for
1213 daylight saving, and its sign is reversed.  In GNU programs it is better
1214 to use @code{tm_gmtoff}, since it contains the correct offset even when
1215 it is not the latest one.
1216 @end deftypevar
1218 @comment time.h
1219 @comment SVID
1220 @deftypevar int daylight
1221 This variable has a nonzero value if daylight savings time rules apply.
1222 A nonzero value does not necessarily mean that daylight savings time is
1223 now in effect; it means only that daylight savings time is sometimes in
1224 effect.
1225 @end deftypevar
1227 @node Time Functions Example
1228 @subsection Time Functions Example
1230 Here is an example program showing the use of some of the local time and
1231 calendar time functions.
1233 @smallexample
1234 @include strftim.c.texi
1235 @end smallexample
1237 It produces output like this:
1239 @smallexample
1240 Wed Jul 31 13:02:36 1991
1241 Today is Wednesday, July 31.
1242 The time is 01:02 PM.
1243 @end smallexample
1246 @node Setting an Alarm
1247 @section Setting an Alarm
1249 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
1250 process to interrupt itself at some future time.  They do this by setting a
1251 timer; when the timer expires, the process receives a signal.
1253 @cindex setting an alarm
1254 @cindex interval timer, setting
1255 @cindex alarms, setting
1256 @cindex timers, setting
1257 Each process has three independent interval timers available:
1259 @itemize @bullet
1260 @item
1261 A real-time timer that counts clock time.  This timer sends a
1262 @code{SIGALRM} signal to the process when it expires.
1263 @cindex real-time timer
1264 @cindex timer, real-time
1266 @item
1267 A virtual timer that counts CPU time used by the process.  This timer
1268 sends a @code{SIGVTALRM} signal to the process when it expires.
1269 @cindex virtual timer
1270 @cindex timer, virtual
1272 @item
1273 A profiling timer that counts both CPU time used by the process, and CPU
1274 time spent in system calls on behalf of the process.  This timer sends a
1275 @code{SIGPROF} signal to the process when it expires.
1276 @cindex profiling timer
1277 @cindex timer, profiling
1279 This timer is useful for profiling in interpreters.  The interval timer
1280 mechanism does not have the fine granularity necessary for profiling
1281 native code.
1282 @c @xref{profil} !!!
1283 @end itemize
1285 You can only have one timer of each kind set at any given time.  If you
1286 set a timer that has not yet expired, that timer is simply reset to the
1287 new value.
1289 You should establish a handler for the appropriate alarm signal using
1290 @code{signal} or @code{sigaction} before issuing a call to @code{setitimer}
1291 or @code{alarm}.  Otherwise, an unusual chain of events could cause the
1292 timer to expire before your program establishes the handler, and in that
1293 case it would be terminated, since that is the default action for the alarm
1294 signals.  @xref{Signal Handling}.
1296 The @code{setitimer} function is the primary means for setting an alarm.
1297 This facility is declared in the header file @file{sys/time.h}.  The
1298 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
1299 simpler interface for setting the real-time timer.
1300 @pindex unistd.h
1301 @pindex sys/time.h
1303 @comment sys/time.h
1304 @comment BSD
1305 @deftp {Data Type} {struct itimerval}
1306 This structure is used to specify when a timer should expire.  It contains
1307 the following members:
1308 @table @code
1309 @item struct timeval it_interval
1310 This is the interval between successive timer interrupts.  If zero, the
1311 alarm will only be sent once.
1313 @item struct timeval it_value
1314 This is the interval to the first timer interrupt.  If zero, the alarm is
1315 disabled.
1316 @end table
1318 The @code{struct timeval} data type is described in @ref{High-Resolution
1319 Calendar}.
1320 @end deftp
1322 @comment sys/time.h
1323 @comment BSD
1324 @deftypefun int setitimer (int @var{which}, struct itimerval *@var{new}, struct itimerval *@var{old})
1325 The @code{setitimer} function sets the timer specified by @var{which}
1326 according to @var{new}.  The @var{which} argument can have a value of
1327 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
1329 If @var{old} is not a null pointer, @code{setitimer} returns information
1330 about any previous unexpired timer of the same kind in the structure it
1331 points to.
1333 The return value is @code{0} on success and @code{-1} on failure.  The
1334 following @code{errno} error conditions are defined for this function:
1336 @table @code
1337 @item EINVAL
1338 The timer interval was too large.
1339 @end table
1340 @end deftypefun
1342 @comment sys/time.h
1343 @comment BSD
1344 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
1345 The @code{getitimer} function stores information about the timer specified
1346 by @var{which} in the structure pointed at by @var{old}.
1348 The return value and error conditions are the same as for @code{setitimer}.
1349 @end deftypefun
1351 @comment sys/time.h
1352 @comment BSD
1353 @table @code
1354 @item ITIMER_REAL
1355 @findex ITIMER_REAL
1356 This constant can be used as the @var{which} argument to the
1357 @code{setitimer} and @code{getitimer} functions to specify the real-time
1358 timer.
1360 @comment sys/time.h
1361 @comment BSD
1362 @item ITIMER_VIRTUAL
1363 @findex ITIMER_VIRTUAL
1364 This constant can be used as the @var{which} argument to the
1365 @code{setitimer} and @code{getitimer} functions to specify the virtual
1366 timer.
1368 @comment sys/time.h
1369 @comment BSD
1370 @item ITIMER_PROF
1371 @findex ITIMER_PROF
1372 This constant can be used as the @var{which} argument to the
1373 @code{setitimer} and @code{getitimer} functions to specify the profiling
1374 timer.
1375 @end table
1377 @comment unistd.h
1378 @comment POSIX.1
1379 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
1380 The @code{alarm} function sets the real-time timer to expire in
1381 @var{seconds} seconds.  If you want to cancel any existing alarm, you
1382 can do this by calling @code{alarm} with a @var{seconds} argument of
1383 zero.
1385 The return value indicates how many seconds remain before the previous
1386 alarm would have been sent.  If there is no previous alarm, @code{alarm}
1387 returns zero.
1388 @end deftypefun
1390 The @code{alarm} function could be defined in terms of @code{setitimer}
1391 like this:
1393 @smallexample
1394 unsigned int
1395 alarm (unsigned int seconds)
1397   struct itimerval old, new;
1398   new.it_interval.tv_usec = 0;
1399   new.it_interval.tv_sec = 0;
1400   new.it_value.tv_usec = 0;
1401   new.it_value.tv_sec = (long int) seconds;
1402   if (setitimer (ITIMER_REAL, &new, &old) < 0)
1403     return 0;
1404   else
1405     return old.it_value.tv_sec;
1407 @end smallexample
1409 There is an example showing the use of the @code{alarm} function in
1410 @ref{Handler Returns}.
1412 If you simply want your process to wait for a given number of seconds,
1413 you should use the @code{sleep} function.  @xref{Sleeping}.
1415 You shouldn't count on the signal arriving precisely when the timer
1416 expires.  In a multiprocessing environment there is typically some
1417 amount of delay involved.
1419 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
1420 functions are derived from BSD Unix, while the @code{alarm} function is
1421 specified by the POSIX.1 standard.  @code{setitimer} is more powerful than
1422 @code{alarm}, but @code{alarm} is more widely used.
1424 @node Sleeping
1425 @section Sleeping
1427 The function @code{sleep} gives a simple way to make the program wait
1428 for short periods of time.  If your program doesn't use signals (except
1429 to terminate), then you can expect @code{sleep} to wait reliably for
1430 the specified amount of time.  Otherwise, @code{sleep} can return sooner
1431 if a signal arrives; if you want to wait for a given period regardless
1432 of signals, use @code{select} (@pxref{Waiting for I/O}) and don't
1433 specify any descriptors to wait for.
1434 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
1436 @comment unistd.h
1437 @comment POSIX.1
1438 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
1439 The @code{sleep} function waits for @var{seconds} or until a signal
1440 is delivered, whichever happens first.
1442 If @code{sleep} function returns because the requested time has
1443 elapsed, it returns a value of zero.  If it returns because of delivery
1444 of a signal, its return value is the remaining time in the sleep period.
1446 The @code{sleep} function is declared in @file{unistd.h}.
1447 @end deftypefun
1449 Resist the temptation to implement a sleep for a fixed amount of time by
1450 using the return value of @code{sleep}, when nonzero, to call
1451 @code{sleep} again.  This will work with a certain amount of accuracy as
1452 long as signals arrive infrequently.  But each signal can cause the
1453 eventual wakeup time to be off by an additional second or so.  Suppose a
1454 few signals happen to arrive in rapid succession by bad luck---there is
1455 no limit on how much this could shorten or lengthen the wait.
1457 Instead, compute the time at which the program should stop waiting, and
1458 keep trying to wait until that time.  This won't be off by more than a
1459 second.  With just a little more work, you can use @code{select} and
1460 make the waiting period quite accurate.  (Of course, heavy system load
1461 can cause unavoidable additional delays---unless the machine is
1462 dedicated to one application, there is no way you can avoid this.)
1464 On some systems, @code{sleep} can do strange things if your program uses
1465 @code{SIGALRM} explicitly.  Even if @code{SIGALRM} signals are being
1466 ignored or blocked when @code{sleep} is called, @code{sleep} might
1467 return prematurely on delivery of a @code{SIGALRM} signal.  If you have
1468 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
1469 signal is delivered while the process is sleeping, the action taken
1470 might be just to cause @code{sleep} to return instead of invoking your
1471 handler.  And, if @code{sleep} is interrupted by delivery of a signal
1472 whose handler requests an alarm or alters the handling of @code{SIGALRM},
1473 this handler and @code{sleep} will interfere.
1475 On the GNU system, it is safe to use @code{sleep} and @code{SIGALRM} in
1476 the same program, because @code{sleep} does not work by means of
1477 @code{SIGALRM}.
1479 @comment time.h
1480 @comment POSIX.1
1481 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
1482 If the resolution of seconds is not enough the @code{nanosleep} function
1483 can be used.  As the name suggests the sleeping period can be specified
1484 in nanoseconds.  The actual period of waiting time might be longer since
1485 the requested time in the @var{requested_time} parameter is rounded up
1486 to the next integer multiple of the actual resolution of the system.
1488 If the function returns because the time has elapsed the return value is
1489 zero.  If the function return @math{-1} the global variable @var{errno}
1490 is set to the following values:
1492 @table @code
1493 @item EINTR
1494 The call was interrupted because a signal was delivered to the thread.
1495 If the @var{remaining} parameter is not the null pointer the structure
1496 pointed to by @var{remaining} is updated to contain the remaining time.
1498 @item EINVAL
1499 The nanosecond value in the @var{requested_time} parameter contains an
1500 illegal value.  Either the value is negative or greater than or equal to
1501 1000 million.
1502 @end table
1504 This function is a cancelation point in multi-threaded programs.  This
1505 is a problem if the thread allocates some resources (like memory, file
1506 descriptors, semaphores or whatever) at the time @code{nanosleep} is
1507 called.  If the thread gets canceled these resources stay allocated
1508 until the program ends.  To avoid this calls to @code{nanosleep} should
1509 be protected using cancelation handlers.
1510 @c ref pthread_cleanup_push / pthread_cleanup_pop
1512 The @code{nanosleep} function is declared in @file{time.h}.
1513 @end deftypefun
1515 @node Resource Usage
1516 @section Resource Usage
1518 @pindex sys/resource.h
1519 The function @code{getrusage} and the data type @code{struct rusage}
1520 are used for examining the usage figures of a process.  They are declared
1521 in @file{sys/resource.h}.
1523 @comment sys/resource.h
1524 @comment BSD
1525 @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
1526 This function reports the usage totals for processes specified by
1527 @var{processes}, storing the information in @code{*@var{rusage}}.
1529 In most systems, @var{processes} has only two valid values:
1531 @table @code
1532 @comment sys/resource.h
1533 @comment BSD
1534 @item RUSAGE_SELF
1535 Just the current process.
1537 @comment sys/resource.h
1538 @comment BSD
1539 @item RUSAGE_CHILDREN
1540 All child processes (direct and indirect) that have terminated already.
1541 @end table
1543 In the GNU system, you can also inquire about a particular child process
1544 by specifying its process ID.
1546 The return value of @code{getrusage} is zero for success, and @code{-1}
1547 for failure.
1549 @table @code
1550 @item EINVAL
1551 The argument @var{processes} is not valid.
1552 @end table
1553 @end deftypefun
1555 One way of getting usage figures for a particular child process is with
1556 the function @code{wait4}, which returns totals for a child when it
1557 terminates.  @xref{BSD Wait Functions}.
1559 @comment sys/resource.h
1560 @comment BSD
1561 @deftp {Data Type} {struct rusage}
1562 This data type records a collection usage amounts for various sorts of
1563 resources.  It has the following members, and possibly others:
1565 @table @code
1566 @item struct timeval ru_utime
1567 Time spent executing user instructions.
1569 @item struct timeval ru_stime
1570 Time spent in operating system code on behalf of @var{processes}.
1572 @item long int ru_maxrss
1573 The maximum resident set size used, in kilobytes.  That is, the maximum
1574 number of kilobytes that @var{processes} used in real memory simultaneously.
1576 @item long int ru_ixrss
1577 An integral value expressed in kilobytes times ticks of execution, which
1578 indicates the amount of memory used by text that was shared with other
1579 processes.
1581 @item long int ru_idrss
1582 An integral value expressed the same way, which is the amount of
1583 unshared memory used in data.
1585 @item long int ru_isrss
1586 An integral value expressed the same way, which is the amount of
1587 unshared memory used in stack space.
1589 @item long int ru_minflt
1590 The number of page faults which were serviced without requiring any I/O.
1592 @item long int ru_majflt
1593 The number of page faults which were serviced by doing I/O.
1595 @item long int ru_nswap
1596 The number of times @var{processes} was swapped entirely out of main memory.
1598 @item long int ru_inblock
1599 The number of times the file system had to read from the disk on behalf
1600 of @var{processes}.
1602 @item long int ru_oublock
1603 The number of times the file system had to write to the disk on behalf
1604 of @var{processes}.
1606 @item long int ru_msgsnd
1607 Number of IPC messages sent.
1609 @item long ru_msgrcv
1610 Number of IPC messages received.
1612 @item long int ru_nsignals
1613 Number of signals received.
1615 @item long int ru_nvcsw
1616 The number of times @var{processes} voluntarily invoked a context switch
1617 (usually to wait for some service).
1619 @item long int ru_nivcsw
1620 The number of times an involuntary context switch took place (because
1621 the time slice expired, or another process of higher priority became
1622 runnable).
1623 @end table
1624 @end deftp
1626 An additional historical function for examining usage figures,
1627 @code{vtimes}, is supported but not documented here.  It is declared in
1628 @file{sys/vtimes.h}.
1630 @node Limits on Resources
1631 @section Limiting Resource Usage
1632 @cindex resource limits
1633 @cindex limits on resource usage
1634 @cindex usage limits
1636 You can specify limits for the resource usage of a process.  When the
1637 process tries to exceed a limit, it may get a signal, or the system call
1638 by which it tried to do so may fail, depending on the limit.  Each
1639 process initially inherits its limit values from its parent, but it can
1640 subsequently change them.
1642 @pindex sys/resource.h
1643 The symbols in this section are defined in @file{sys/resource.h}.
1645 @comment sys/resource.h
1646 @comment BSD
1647 @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
1648 Read the current value and the maximum value of resource @var{resource}
1649 and store them in @code{*@var{rlp}}.
1651 The return value is @code{0} on success and @code{-1} on failure.  The
1652 only possible @code{errno} error condition is @code{EFAULT}.
1654 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1655 32 bits system this function is in fact @code{getrlimit64}.  I.e., the
1656 LFS interface transparently replaces the old interface.
1657 @end deftypefun
1659 @comment sys/resource.h
1660 @comment Unix98
1661 @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
1662 This function is similar to the @code{getrlimit} but its second
1663 parameter is a pointer to a variable of type @code{struct rlimit64}
1664 which allows this function to read values which wouldn't fit in the
1665 member of a @code{struct rlimit}.
1667 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
1668 bits machine this function is available under the name @code{getrlimit}
1669 and so transparently replaces the old interface.
1670 @end deftypefun
1672 @comment sys/resource.h
1673 @comment BSD
1674 @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
1675 Store the current value and the maximum value of resource @var{resource}
1676 in @code{*@var{rlp}}.
1678 The return value is @code{0} on success and @code{-1} on failure.  The
1679 following @code{errno} error condition is possible:
1681 @table @code
1682 @item EPERM
1683 You tried to change the maximum permissible limit value,
1684 but you don't have privileges to do so.
1685 @end table
1687 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1688 32 bits system this function is in fact @code{setrlimit64}.  I.e., the
1689 LFS interface transparently replaces the old interface.
1690 @end deftypefun
1692 @comment sys/resource.h
1693 @comment Unix98
1694 @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
1695 This function is similar to the @code{setrlimit} but its second
1696 parameter is a pointer to a variable of type @code{struct rlimit64}
1697 which allows this function to set values which wouldn't fit in the
1698 member of a @code{struct rlimit}.
1700 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
1701 bits machine this function is available under the name @code{setrlimit}
1702 and so transparently replaces the old interface.
1703 @end deftypefun
1705 @comment sys/resource.h
1706 @comment BSD
1707 @deftp {Data Type} {struct rlimit}
1708 This structure is used with @code{getrlimit} to receive limit values,
1709 and with @code{setrlimit} to specify limit values.  It has two fields:
1711 @table @code
1712 @item rlim_t rlim_cur
1713 The current value of the limit in question.
1714 This is also called the ``soft limit''.
1715 @cindex soft limit
1717 @item rlim_t rlim_max
1718 The maximum permissible value of the limit in question.  You cannot set
1719 the current value of the limit to a larger number than this maximum.
1720 Only the super user can change the maximum permissible value.
1721 This is also called the ``hard limit''.
1722 @cindex hard limit
1723 @end table
1725 In @code{getrlimit}, the structure is an output; it receives the current
1726 values.  In @code{setrlimit}, it specifies the new values.
1727 @end deftp
1729 For the LFS functions a similar type is defined in @file{sys/resource.h}.
1731 @comment sys/resource.h
1732 @comment Unix98
1733 @deftp {Data Type} {struct rlimit64}
1734 This structure is used with @code{getrlimit64} to receive limit values,
1735 and with @code{setrlimit64} to specify limit values.  It has two fields:
1737 @table @code
1738 @item rlim64_t rlim_cur
1739 The current value of the limit in question.
1740 This is also called the ``soft limit''.
1742 @item rlim64_t rlim_max
1743 The maximum permissible value of the limit in question.  You cannot set
1744 the current value of the limit to a larger number than this maximum.
1745 Only the super user can change the maximum permissible value.
1746 This is also called the ``hard limit''.
1747 @end table
1749 In @code{getrlimit64}, the structure is an output; it receives the current
1750 values.  In @code{setrlimit64}, it specifies the new values.
1751 @end deftp
1753 Here is a list of resources that you can specify a limit for.
1754 Those that are sizes are measured in bytes.
1756 @table @code
1757 @comment sys/resource.h
1758 @comment BSD
1759 @item RLIMIT_CPU
1760 @vindex RLIMIT_CPU
1761 The maximum amount of cpu time the process can use.  If it runs for
1762 longer than this, it gets a signal: @code{SIGXCPU}.  The value is
1763 measured in seconds.  @xref{Operation Error Signals}.
1765 @comment sys/resource.h
1766 @comment BSD
1767 @item RLIMIT_FSIZE
1768 @vindex RLIMIT_FSIZE
1769 The maximum size of file the process can create.  Trying to write a
1770 larger file causes a signal: @code{SIGXFSZ}.  @xref{Operation Error
1771 Signals}.
1773 @comment sys/resource.h
1774 @comment BSD
1775 @item RLIMIT_DATA
1776 @vindex RLIMIT_DATA
1777 The maximum size of data memory for the process.  If the process tries
1778 to allocate data memory beyond this amount, the allocation function
1779 fails.
1781 @comment sys/resource.h
1782 @comment BSD
1783 @item RLIMIT_STACK
1784 @vindex RLIMIT_STACK
1785 The maximum stack size for the process.  If the process tries to extend
1786 its stack past this size, it gets a @code{SIGSEGV} signal.
1787 @xref{Program Error Signals}.
1789 @comment sys/resource.h
1790 @comment BSD
1791 @item RLIMIT_CORE
1792 @vindex RLIMIT_CORE
1793 The maximum size core file that this process can create.  If the process
1794 terminates and would dump a core file larger than this maximum size,
1795 then no core file is created.  So setting this limit to zero prevents
1796 core files from ever being created.
1798 @comment sys/resource.h
1799 @comment BSD
1800 @item RLIMIT_RSS
1801 @vindex RLIMIT_RSS
1802 The maximum amount of physical memory that this process should get.
1803 This parameter is a guide for the system's scheduler and memory
1804 allocator; the system may give the process more memory when there is a
1805 surplus.
1807 @comment sys/resource.h
1808 @comment BSD
1809 @item RLIMIT_MEMLOCK
1810 The maximum amount of memory that can be locked into physical memory (so
1811 it will never be paged out).
1813 @comment sys/resource.h
1814 @comment BSD
1815 @item RLIMIT_NPROC
1816 The maximum number of processes that can be created with the same user ID.
1817 If you have reached the limit for your user ID, @code{fork} will fail
1818 with @code{EAGAIN}.  @xref{Creating a Process}.
1820 @comment sys/resource.h
1821 @comment BSD
1822 @item RLIMIT_NOFILE
1823 @vindex RLIMIT_NOFILE
1824 @itemx RLIMIT_OFILE
1825 @vindex RLIMIT_OFILE
1826 The maximum number of files that the process can open.  If it tries to
1827 open more files than this, it gets error code @code{EMFILE}.
1828 @xref{Error Codes}.  Not all systems support this limit; GNU does, and
1829 4.4 BSD does.
1831 @comment sys/resource.h
1832 @comment BSD
1833 @item RLIM_NLIMITS
1834 @vindex RLIM_NLIMITS
1835 The number of different resource limits.  Any valid @var{resource}
1836 operand must be less than @code{RLIM_NLIMITS}.
1837 @end table
1839 @comment sys/resource.h
1840 @comment BSD
1841 @deftypevr Constant int RLIM_INFINITY
1842 This constant stands for a value of ``infinity'' when supplied as
1843 the limit value in @code{setrlimit}.
1844 @end deftypevr
1846 @c ??? Someone want to finish these?
1847 Two historical functions for setting resource limits, @code{ulimit} and
1848 @code{vlimit}, are not documented here.  The latter is declared in
1849 @file{sys/vlimit.h} and comes from BSD.
1851 @node Priority
1852 @section Process Priority
1853 @cindex process priority
1854 @cindex priority of a process
1856 @pindex sys/resource.h
1857 When several processes try to run, their respective priorities determine
1858 what share of the CPU each process gets.  This section describes how you
1859 can read and set the priority of a process.  All these functions and
1860 macros are declared in @file{sys/resource.h}.
1862 The range of valid priority values depends on the operating system, but
1863 typically it runs from @code{-20} to @code{20}.  A lower priority value
1864 means the process runs more often.  These constants describe the range of
1865 priority values:
1867 @table @code
1868 @comment sys/resource.h
1869 @comment BSD
1870 @item PRIO_MIN
1871 @vindex PRIO_MIN
1872 The smallest valid priority value.
1874 @comment sys/resource.h
1875 @comment BSD
1876 @item PRIO_MAX
1877 @vindex PRIO_MAX
1878 The largest valid priority value.
1879 @end table
1881 @comment sys/resource.h
1882 @comment BSD
1883 @deftypefun int getpriority (int @var{class}, int @var{id})
1884 Read the priority of a class of processes; @var{class} and @var{id}
1885 specify which ones (see below).  If the processes specified do not all
1886 have the same priority, this returns the smallest value that any of them
1887 has.
1889 The return value is the priority value on success, and @code{-1} on
1890 failure.  The following @code{errno} error condition are possible for
1891 this function:
1893 @table @code
1894 @item ESRCH
1895 The combination of @var{class} and @var{id} does not match any existing
1896 process.
1898 @item EINVAL
1899 The value of @var{class} is not valid.
1900 @end table
1902 When the return value is @code{-1}, it could indicate failure, or it
1903 could be the priority value.  The only way to make certain is to set
1904 @code{errno = 0} before calling @code{getpriority}, then use @code{errno
1905 != 0} afterward as the criterion for failure.
1906 @end deftypefun
1908 @comment sys/resource.h
1909 @comment BSD
1910 @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{priority})
1911 Set the priority of a class of processes to @var{priority}; @var{class}
1912 and @var{id} specify which ones (see below).
1914 The return value is @code{0} on success and @code{-1} on failure.  The
1915 following @code{errno} error condition are defined for this function:
1917 @table @code
1918 @item ESRCH
1919 The combination of @var{class} and @var{id} does not match any existing
1920 process.
1922 @item EINVAL
1923 The value of @var{class} is not valid.
1925 @item EPERM
1926 You tried to set the priority of some other user's process, and you
1927 don't have privileges for that.
1929 @item EACCES
1930 You tried to lower the priority of a process, and you don't have
1931 privileges for that.
1932 @end table
1933 @end deftypefun
1935 The arguments @var{class} and @var{id} together specify a set of
1936 processes you are interested in.  These are the possible values for
1937 @var{class}:
1939 @table @code
1940 @comment sys/resource.h
1941 @comment BSD
1942 @item PRIO_PROCESS
1943 @vindex PRIO_PROCESS
1944 Read or set the priority of one process.  The argument @var{id} is a
1945 process ID.
1947 @comment sys/resource.h
1948 @comment BSD
1949 @item PRIO_PGRP
1950 @vindex PRIO_PGRP
1951 Read or set the priority of one process group.  The argument @var{id} is
1952 a process group ID.
1954 @comment sys/resource.h
1955 @comment BSD
1956 @item PRIO_USER
1957 @vindex PRIO_USER
1958 Read or set the priority of one user's processes.  The argument @var{id}
1959 is a user ID.
1960 @end table
1962 If the argument @var{id} is 0, it stands for the current process,
1963 current process group, or the current user, according to @var{class}.
1965 @c ??? I don't know where we should say this comes from.
1966 @comment Unix
1967 @comment dunno.h
1968 @deftypefun int nice (int @var{increment})
1969 Increment the priority of the current process by @var{increment}.
1970 The return value is the same as for @code{setpriority}.
1972 Here is an equivalent definition for @code{nice}:
1974 @smallexample
1976 nice (int increment)
1978   int old = getpriority (PRIO_PROCESS, 0);
1979   return setpriority (PRIO_PROCESS, 0, old + increment);
1981 @end smallexample
1982 @end deftypefun