1 @node Date and Time, Non-Local Exits, Arithmetic, Top
2 @c %MENU% Functions for getting the date and time and formatting them nicely
5 This chapter describes functions for manipulating dates and times,
6 including functions for determining what the current time is and
7 conversion between different time representations.
9 The time functions fall into three main categories:
13 Functions for measuring elapsed CPU time are discussed in @ref{Processor
17 Functions for measuring absolute clock or calendar time are discussed in
21 Functions for setting alarms and timers are discussed in @ref{Setting
26 * Processor Time:: Measures processor time used by a program.
27 * Calendar Time:: Manipulation of ``real'' dates and times.
28 * Setting an Alarm:: Sending a signal after a specified time.
29 * Sleeping:: Waiting for a period of time.
30 * Resource Usage:: Measuring various resources used.
31 * Limits on Resources:: Specifying limits on resource usage.
32 * Priority:: Reading or setting process run priority.
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.
47 @cindex processor time
50 @cindex time, elapsed CPU
53 * Basic CPU Time:: The @code{clock} function.
54 * Detailed CPU Time:: The @code{times} function.
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
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:
77 @dots{} /* @r{Do the work.} */
79 elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
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
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.
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.
105 @deftypevr Macro int CLK_TCK
106 This is an obsolete name for @code{CLOCKS_PER_SEC}.
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.
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)}.
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.
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:
141 @item clock_t tms_utime
142 This is the CPU time used in executing the instructions of the calling
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
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
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}.
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.
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
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:
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
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
210 @cindex high-resolution time
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.
219 @cindex broken-down time
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
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}.
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
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.
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.
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}.
295 @deftp {Data Type} {struct timeval}
296 The @code{struct timeval} structure represents a calendar time. It
297 has the following members:
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
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.
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:
321 @item int tz_minuteswest
322 This is the number of minutes west of UTC.
325 If nonzero, daylight saving time applies during some part of the year.
328 The @code{struct timezone} type is obsolete and should never be used.
329 Instead, use the facilities described in @ref{Time Zone Functions}.
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
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;
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;
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;
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:
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}.
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:
403 This process cannot set the time because it is not privileged.
406 The operating system does not support setting time zone information, and
407 @var{tzp} is not a null pointer.
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:
435 You do not have privilege to set the time.
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}.
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:
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.)
474 This is the number of minutes after the hour, in the range @code{0} through
478 This is the number of hours past midnight, in the range @code{0} through
482 This is the day of the month, in the range @code{1} through @code{31}.
485 This is the number of months since January, in the range @code{0} through
489 This is the number of years since @code{1900}.
492 This is the number of days since Sunday, in the range @code{0} through
496 This is the number of days since January 1, in the range @code{0} through
500 @cindex Daylight Saving 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.
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
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
539 Calling @code{localtime} has one other effect: it sets the variable
540 @code{tzname} with information about the current time zone. @xref{Time
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.
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}.
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
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
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}.
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}.
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}.
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:
628 "Tue May 21 13:46:22 1991\n"
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
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
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
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
666 asctime (localtime (@var{time}))
669 @code{ctime} sets the variable @code{tzname}, because @code{localtime}
670 does so. @xref{Time Zone Functions}.
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, @xref{Statement Exprs,,,gcc,Porting and Using gcc}.):
681 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
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
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
709 The number is padded with spaces.
712 The number is not padded at all.
715 The number is padded with zeros even if the format specifies padding
719 The output uses uppercase characters, but only if this is possible
720 (@pxref{Case Conversion}).
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
733 An optional modifier can follow the optional flag and width
734 specification. The modifiers, which are POSIX.2 extensions, are:
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
745 Use the locale's alternate numeric symbols for numbers. This modifier
746 applies only to numeric format specifiers.
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
758 The abbreviated weekday name according to the current locale.
761 The full weekday name according to the current locale.
764 The abbreviated month name according to the current locale.
767 The full month name according to the current locale.
770 The preferred date and time representation for the current locale.
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.
779 The day of the month as a decimal number (range @code{01} through @code{31}).
782 The date using the format @code{%m/%d/%y}.
784 This format is a POSIX.2 extension.
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.
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.
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.
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.
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
818 This format is a GNU extension.
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.
827 The hour as a decimal number, using a 24-hour clock (range @code{00} through
831 The hour as a decimal number, using a 12-hour clock (range @code{01} through
835 The day of the year as a decimal number (range @code{001} through @code{366}).
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.
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.
850 The month as a decimal number (range @code{01} through @code{12}).
853 The minute as a decimal number (range @code{00} through @code{59}).
856 A single @samp{\n} (newline) character.
858 This format is a POSIX.2 extension.
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}.
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.
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.
877 The complete time using the AM/PM format of the current locale.
879 This format is a POSIX.2 extension.
882 The hour and minute in decimal numbers using the format @code{%H:%M}.
884 This format is a GNU extension.
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.
893 The second as a decimal number (range @code{00} through @code{60}).
896 A single @samp{\t} (tabulator) character.
898 This format is a POSIX.2 extension.
901 The time using decimal numbers using the format @code{%H:%M:%S}.
903 This format is a POSIX.2 extension.
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.
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}.
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
928 This format is a POSIX.2 extension.
931 The day of the week as a decimal number (range @code{0} through
932 @code{6}), Sunday being @code{0}.
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}.
941 The preferred date representation for the current locale, but without the
945 The preferred time representation for the current locale, but with no date.
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.
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.
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
960 This format is a GNU extension.
963 The time zone abbreviation (empty if the time zone can't be determined).
966 A literal @samp{%} character.
969 The @var{size} parameter can be used to specify the maximum number of
970 characters to be stored in the array @var{s}, including the terminating
971 null character. If the formatted time requires more than @var{size}
972 characters, @code{strftime} returns zero and the content of the array
973 @var{s} is indetermined. Otherwise the return value indicates the
974 number of characters placed in the array @var{s}, not including the
975 terminating null character.
977 @emph{Warning:} This convention for the return value which is prescribed
978 in @w{ISO C} can lead to problems in some situations. For certain
979 format strings and certain locales the output really can be the empty
980 string and this cannot be discovered by testing the return value only.
981 E.g., in most locales the AM/PM time format is not supported (most of
982 the world uses the 24 hour time representation). In such locales
983 @code{"%p"} will return the empty string, i.e., the return value is
984 zero. To detect situations like this something similar to the following
989 len = strftime (buf, bufsize, format, tp);
990 if (len == 0 && buf[0] != '\0')
992 /* Something went wrong in the strftime call. */
997 If @var{s} is a null pointer, @code{strftime} does not actually write
998 anything, but instead returns the number of characters it would have written.
1000 According to POSIX.1 every call to @code{strftime} implies a call to
1001 @code{tzset}. So the contents of the environment variable @code{TZ}
1002 is examined before any output is produced.
1004 For an example of @code{strftime}, see @ref{Time Functions Example}.
1008 @subsection Specifying the Time Zone with @code{TZ}
1010 In POSIX systems, a user can specify the time zone by means of the
1011 @code{TZ} environment variable. For information about how to set
1012 environment variables, see @ref{Environment Variables}. The functions
1013 for accessing the time zone are declared in @file{time.h}.
1017 You should not normally need to set @code{TZ}. If the system is
1018 configured properly, the default time zone will be correct. You might
1019 set @code{TZ} if you are using a computer over the network from a
1020 different time zone, and would like times reported to you in the time zone
1021 that local for you, rather than what is local for the computer.
1023 In POSIX.1 systems the value of the @code{TZ} variable can be of one of
1024 three formats. With the GNU C library, the most common format is the
1025 last one, which can specify a selection from a large database of time
1026 zone information for many regions of the world. The first two formats
1027 are used to describe the time zone information directly, which is both
1028 more cumbersome and less precise. But the POSIX.1 standard only
1029 specifies the details of the first two formats, so it is good to be
1030 familiar with them in case you come across a POSIX.1 system that doesn't
1031 support a time zone information database.
1033 The first format is used when there is no Daylight Saving Time (or
1034 summer time) in the local time zone:
1037 @r{@var{std} @var{offset}}
1040 The @var{std} string specifies the name of the time zone. It must be
1041 three or more characters long and must not contain a leading colon or
1042 embedded digits, commas, or plus or minus signs. There is no space
1043 character separating the time zone name from the @var{offset}, so these
1044 restrictions are necessary to parse the specification correctly.
1046 The @var{offset} specifies the time value one must add to the local time
1047 to get a Coordinated Universal Time value. It has syntax like
1048 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]]. This
1049 is positive if the local time zone is west of the Prime Meridian and
1050 negative if it is east. The hour must be between @code{0} and
1051 @code{23}, and the minute and seconds between @code{0} and @code{59}.
1053 For example, here is how we would specify Eastern Standard Time, but
1054 without any daylight saving time alternative:
1060 The second format is used when there is Daylight Saving Time:
1063 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
1066 The initial @var{std} and @var{offset} specify the standard time zone, as
1067 described above. The @var{dst} string and @var{offset} specify the name
1068 and offset for the corresponding daylight saving time zone; if the
1069 @var{offset} is omitted, it defaults to one hour ahead of standard time.
1071 The remainder of the specification describes when daylight saving time is
1072 in effect. The @var{start} field is when daylight saving time goes into
1073 effect and the @var{end} field is when the change is made back to standard
1074 time. The following formats are recognized for these fields:
1078 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
1079 February 29 is never counted, even in leap years.
1082 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
1083 February 29 is counted in leap years.
1085 @item M@var{m}.@var{w}.@var{d}
1086 This specifies day @var{d} of week @var{w} of month @var{m}. The day
1087 @var{d} must be between @code{0} (Sunday) and @code{6}. The week
1088 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
1089 first week in which day @var{d} occurs, and week @code{5} specifies the
1090 @emph{last} @var{d} day in the month. The month @var{m} should be
1091 between @code{1} and @code{12}.
1094 The @var{time} fields specify when, in the local time currently in
1095 effect, the change to the other time occurs. If omitted, the default is
1098 For example, here is how one would specify the Eastern time zone in the
1099 United States, including the appropriate daylight saving time and its dates
1100 of applicability. The normal offset from UTC is 5 hours; since this is
1101 west of the prime meridian, the sign is positive. Summer time begins on
1102 the first Sunday in April at 2:00am, and ends on the last Sunday in October
1106 EST+5EDT,M4.1.0/2,M10.5.0/2
1109 The schedule of daylight saving time in any particular jurisdiction has
1110 changed over the years. To be strictly correct, the conversion of dates
1111 and times in the past should be based on the schedule that was in effect
1112 then. However, this format has no facilities to let you specify how the
1113 schedule has changed from year to year. The most you can do is specify
1114 one particular schedule---usually the present day schedule---and this is
1115 used to convert any date, no matter when. For precise time zone
1116 specifications, it is best to use the time zone information database
1119 The third format looks like this:
1125 Each operating system interprets this format differently; in the GNU C
1126 library, @var{characters} is the name of a file which describes the time
1129 @pindex /etc/localtime
1131 If the @code{TZ} environment variable does not have a value, the
1132 operation chooses a time zone by default. In the GNU C library, the
1133 default time zone is like the specification @samp{TZ=:/etc/localtime}
1134 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how GNU C library
1135 was configured; @pxref{Installation}). Other C libraries use their own
1136 rule for choosing the default time zone, so there is little we can say
1139 @cindex time zone database
1140 @pindex /share/lib/zoneinfo
1142 If @var{characters} begins with a slash, it is an absolute file name;
1143 otherwise the library looks for the file
1144 @w{@file{/share/lib/zoneinfo/@var{characters}}}. The @file{zoneinfo}
1145 directory contains data files describing local time zones in many
1146 different parts of the world. The names represent major cities, with
1147 subdirectories for geographical areas; for example,
1148 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
1149 These data files are installed by the system administrator, who also
1150 sets @file{/etc/localtime} to point to the data file for the local time
1151 zone. The GNU C library comes with a large database of time zone
1152 information for most regions of the world, which is maintained by a
1153 community of volunteers and put in the public domain.
1155 @node Time Zone Functions
1156 @subsection Functions and Variables for Time Zones
1160 @deftypevar {char *} tzname [2]
1161 The array @code{tzname} contains two strings, which are the standard
1162 names of the pair of time zones (standard and daylight
1163 saving) that the user has selected. @code{tzname[0]} is the name of
1164 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
1165 is the name for the time zone when daylight saving time is in use (for
1166 example, @code{"EDT"}). These correspond to the @var{std} and @var{dst}
1167 strings (respectively) from the @code{TZ} environment variable. If
1168 daylight saving time is never used, @code{tzname[1]} is the empty string.
1170 The @code{tzname} array is initialized from the @code{TZ} environment
1171 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
1172 @code{mktime}, or @code{localtime} is called. If multiple abbreviations
1173 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
1174 Time and Eastern Daylight Time), the array contains the most recent
1177 The @code{tzname} array is required for POSIX.1 compatibility, but in
1178 GNU programs it is better to use the @code{tm_zone} member of the
1179 broken-down time structure, since @code{tm_zone} reports the correct
1180 abbreviation even when it is not the latest one.
1182 Though the strings are declared as @code{char *} the user must stay away
1183 from modifying these strings. Modifying the strings will almost certainly
1190 @deftypefun void tzset (void)
1191 The @code{tzset} function initializes the @code{tzname} variable from
1192 the value of the @code{TZ} environment variable. It is not usually
1193 necessary for your program to call this function, because it is called
1194 automatically when you use the other time conversion functions that
1195 depend on the time zone.
1198 The following variables are defined for compatibility with System V
1199 Unix. Like @code{tzname}, these variables are set by calling
1200 @code{tzset} or the other time conversion functions.
1204 @deftypevar {long int} timezone
1205 This contains the difference between UTC and the latest local standard
1206 time, in seconds west of UTC. For example, in the U.S. Eastern time
1207 zone, the value is @code{5*60*60}. Unlike the @code{tm_gmtoff} member
1208 of the broken-down time structure, this value is not adjusted for
1209 daylight saving, and its sign is reversed. In GNU programs it is better
1210 to use @code{tm_gmtoff}, since it contains the correct offset even when
1211 it is not the latest one.
1216 @deftypevar int daylight
1217 This variable has a nonzero value if daylight savings time rules apply.
1218 A nonzero value does not necessarily mean that daylight savings time is
1219 now in effect; it means only that daylight savings time is sometimes in
1223 @node Time Functions Example
1224 @subsection Time Functions Example
1226 Here is an example program showing the use of some of the local time and
1227 calendar time functions.
1230 @include strftim.c.texi
1233 It produces output like this:
1236 Wed Jul 31 13:02:36 1991
1237 Today is Wednesday, July 31.
1238 The time is 01:02 PM.
1242 @node Setting an Alarm
1243 @section Setting an Alarm
1245 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
1246 process to interrupt itself at some future time. They do this by setting a
1247 timer; when the timer expires, the process receives a signal.
1249 @cindex setting an alarm
1250 @cindex interval timer, setting
1251 @cindex alarms, setting
1252 @cindex timers, setting
1253 Each process has three independent interval timers available:
1257 A real-time timer that counts clock time. This timer sends a
1258 @code{SIGALRM} signal to the process when it expires.
1259 @cindex real-time timer
1260 @cindex timer, real-time
1263 A virtual timer that counts CPU time used by the process. This timer
1264 sends a @code{SIGVTALRM} signal to the process when it expires.
1265 @cindex virtual timer
1266 @cindex timer, virtual
1269 A profiling timer that counts both CPU time used by the process, and CPU
1270 time spent in system calls on behalf of the process. This timer sends a
1271 @code{SIGPROF} signal to the process when it expires.
1272 @cindex profiling timer
1273 @cindex timer, profiling
1275 This timer is useful for profiling in interpreters. The interval timer
1276 mechanism does not have the fine granularity necessary for profiling
1278 @c @xref{profil} !!!
1281 You can only have one timer of each kind set at any given time. If you
1282 set a timer that has not yet expired, that timer is simply reset to the
1285 You should establish a handler for the appropriate alarm signal using
1286 @code{signal} or @code{sigaction} before issuing a call to @code{setitimer}
1287 or @code{alarm}. Otherwise, an unusual chain of events could cause the
1288 timer to expire before your program establishes the handler, and in that
1289 case it would be terminated, since that is the default action for the alarm
1290 signals. @xref{Signal Handling}.
1292 The @code{setitimer} function is the primary means for setting an alarm.
1293 This facility is declared in the header file @file{sys/time.h}. The
1294 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
1295 simpler interface for setting the real-time timer.
1301 @deftp {Data Type} {struct itimerval}
1302 This structure is used to specify when a timer should expire. It contains
1303 the following members:
1305 @item struct timeval it_interval
1306 This is the interval between successive timer interrupts. If zero, the
1307 alarm will only be sent once.
1309 @item struct timeval it_value
1310 This is the interval to the first timer interrupt. If zero, the alarm is
1314 The @code{struct timeval} data type is described in @ref{High-Resolution
1320 @deftypefun int setitimer (int @var{which}, struct itimerval *@var{new}, struct itimerval *@var{old})
1321 The @code{setitimer} function sets the timer specified by @var{which}
1322 according to @var{new}. The @var{which} argument can have a value of
1323 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
1325 If @var{old} is not a null pointer, @code{setitimer} returns information
1326 about any previous unexpired timer of the same kind in the structure it
1329 The return value is @code{0} on success and @code{-1} on failure. The
1330 following @code{errno} error conditions are defined for this function:
1334 The timer interval was too large.
1340 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
1341 The @code{getitimer} function stores information about the timer specified
1342 by @var{which} in the structure pointed at by @var{old}.
1344 The return value and error conditions are the same as for @code{setitimer}.
1352 This constant can be used as the @var{which} argument to the
1353 @code{setitimer} and @code{getitimer} functions to specify the real-time
1358 @item ITIMER_VIRTUAL
1359 @findex ITIMER_VIRTUAL
1360 This constant can be used as the @var{which} argument to the
1361 @code{setitimer} and @code{getitimer} functions to specify the virtual
1368 This constant can be used as the @var{which} argument to the
1369 @code{setitimer} and @code{getitimer} functions to specify the profiling
1375 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
1376 The @code{alarm} function sets the real-time timer to expire in
1377 @var{seconds} seconds. If you want to cancel any existing alarm, you
1378 can do this by calling @code{alarm} with a @var{seconds} argument of
1381 The return value indicates how many seconds remain before the previous
1382 alarm would have been sent. If there is no previous alarm, @code{alarm}
1386 The @code{alarm} function could be defined in terms of @code{setitimer}
1391 alarm (unsigned int seconds)
1393 struct itimerval old, new;
1394 new.it_interval.tv_usec = 0;
1395 new.it_interval.tv_sec = 0;
1396 new.it_value.tv_usec = 0;
1397 new.it_value.tv_sec = (long int) seconds;
1398 if (setitimer (ITIMER_REAL, &new, &old) < 0)
1401 return old.it_value.tv_sec;
1405 There is an example showing the use of the @code{alarm} function in
1406 @ref{Handler Returns}.
1408 If you simply want your process to wait for a given number of seconds,
1409 you should use the @code{sleep} function. @xref{Sleeping}.
1411 You shouldn't count on the signal arriving precisely when the timer
1412 expires. In a multiprocessing environment there is typically some
1413 amount of delay involved.
1415 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
1416 functions are derived from BSD Unix, while the @code{alarm} function is
1417 specified by the POSIX.1 standard. @code{setitimer} is more powerful than
1418 @code{alarm}, but @code{alarm} is more widely used.
1423 The function @code{sleep} gives a simple way to make the program wait
1424 for short periods of time. If your program doesn't use signals (except
1425 to terminate), then you can expect @code{sleep} to wait reliably for
1426 the specified amount of time. Otherwise, @code{sleep} can return sooner
1427 if a signal arrives; if you want to wait for a given period regardless
1428 of signals, use @code{select} (@pxref{Waiting for I/O}) and don't
1429 specify any descriptors to wait for.
1430 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
1434 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
1435 The @code{sleep} function waits for @var{seconds} or until a signal
1436 is delivered, whichever happens first.
1438 If @code{sleep} function returns because the requested time has
1439 elapsed, it returns a value of zero. If it returns because of delivery
1440 of a signal, its return value is the remaining time in the sleep period.
1442 The @code{sleep} function is declared in @file{unistd.h}.
1445 Resist the temptation to implement a sleep for a fixed amount of time by
1446 using the return value of @code{sleep}, when nonzero, to call
1447 @code{sleep} again. This will work with a certain amount of accuracy as
1448 long as signals arrive infrequently. But each signal can cause the
1449 eventual wakeup time to be off by an additional second or so. Suppose a
1450 few signals happen to arrive in rapid succession by bad luck---there is
1451 no limit on how much this could shorten or lengthen the wait.
1453 Instead, compute the time at which the program should stop waiting, and
1454 keep trying to wait until that time. This won't be off by more than a
1455 second. With just a little more work, you can use @code{select} and
1456 make the waiting period quite accurate. (Of course, heavy system load
1457 can cause unavoidable additional delays---unless the machine is
1458 dedicated to one application, there is no way you can avoid this.)
1460 On some systems, @code{sleep} can do strange things if your program uses
1461 @code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being
1462 ignored or blocked when @code{sleep} is called, @code{sleep} might
1463 return prematurely on delivery of a @code{SIGALRM} signal. If you have
1464 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
1465 signal is delivered while the process is sleeping, the action taken
1466 might be just to cause @code{sleep} to return instead of invoking your
1467 handler. And, if @code{sleep} is interrupted by delivery of a signal
1468 whose handler requests an alarm or alters the handling of @code{SIGALRM},
1469 this handler and @code{sleep} will interfere.
1471 On the GNU system, it is safe to use @code{sleep} and @code{SIGALRM} in
1472 the same program, because @code{sleep} does not work by means of
1477 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
1478 If the resolution of seconds is not enough the @code{nanosleep} function
1479 can be used. As the name suggests the sleeping period can be specified
1480 in nanoseconds. The actual period of waiting time might be longer since
1481 the requested time in the @var{requested_time} parameter is rounded up
1482 to the next integer multiple of the actual resolution of the system.
1484 If the function returns because the time has elapsed the return value is
1485 zero. If the function return @math{-1} the global variable @var{errno}
1486 is set to the following values:
1490 The call was interrupted because a signal was delivered to the thread.
1491 If the @var{remaining} parameter is not the null pointer the structure
1492 pointed to by @var{remaining} is updated to contain the remaining time.
1495 The nanosecond value in the @var{requested_time} parameter contains an
1496 illegal value. Either the value is negative or greater than or equal to
1500 This function is a cancelation point in multi-threaded programs. This
1501 is a problem if the thread allocates some resources (like memory, file
1502 descriptors, semaphores or whatever) at the time @code{nanosleep} is
1503 called. If the thread gets canceled these resources stay allocated
1504 until the program ends. To avoid this calls to @code{nanosleep} should
1505 be protected using cancelation handlers.
1506 @c ref pthread_cleanup_push / pthread_cleanup_pop
1508 The @code{nanosleep} function is declared in @file{time.h}.
1511 @node Resource Usage
1512 @section Resource Usage
1514 @pindex sys/resource.h
1515 The function @code{getrusage} and the data type @code{struct rusage}
1516 are used for examining the usage figures of a process. They are declared
1517 in @file{sys/resource.h}.
1519 @comment sys/resource.h
1521 @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
1522 This function reports the usage totals for processes specified by
1523 @var{processes}, storing the information in @code{*@var{rusage}}.
1525 In most systems, @var{processes} has only two valid values:
1528 @comment sys/resource.h
1531 Just the current process.
1533 @comment sys/resource.h
1535 @item RUSAGE_CHILDREN
1536 All child processes (direct and indirect) that have terminated already.
1539 In the GNU system, you can also inquire about a particular child process
1540 by specifying its process ID.
1542 The return value of @code{getrusage} is zero for success, and @code{-1}
1547 The argument @var{processes} is not valid.
1551 One way of getting usage figures for a particular child process is with
1552 the function @code{wait4}, which returns totals for a child when it
1553 terminates. @xref{BSD Wait Functions}.
1555 @comment sys/resource.h
1557 @deftp {Data Type} {struct rusage}
1558 This data type records a collection usage amounts for various sorts of
1559 resources. It has the following members, and possibly others:
1562 @item struct timeval ru_utime
1563 Time spent executing user instructions.
1565 @item struct timeval ru_stime
1566 Time spent in operating system code on behalf of @var{processes}.
1568 @item long int ru_maxrss
1569 The maximum resident set size used, in kilobytes. That is, the maximum
1570 number of kilobytes that @var{processes} used in real memory simultaneously.
1572 @item long int ru_ixrss
1573 An integral value expressed in kilobytes times ticks of execution, which
1574 indicates the amount of memory used by text that was shared with other
1577 @item long int ru_idrss
1578 An integral value expressed the same way, which is the amount of
1579 unshared memory used in data.
1581 @item long int ru_isrss
1582 An integral value expressed the same way, which is the amount of
1583 unshared memory used in stack space.
1585 @item long int ru_minflt
1586 The number of page faults which were serviced without requiring any I/O.
1588 @item long int ru_majflt
1589 The number of page faults which were serviced by doing I/O.
1591 @item long int ru_nswap
1592 The number of times @var{processes} was swapped entirely out of main memory.
1594 @item long int ru_inblock
1595 The number of times the file system had to read from the disk on behalf
1598 @item long int ru_oublock
1599 The number of times the file system had to write to the disk on behalf
1602 @item long int ru_msgsnd
1603 Number of IPC messages sent.
1605 @item long ru_msgrcv
1606 Number of IPC messages received.
1608 @item long int ru_nsignals
1609 Number of signals received.
1611 @item long int ru_nvcsw
1612 The number of times @var{processes} voluntarily invoked a context switch
1613 (usually to wait for some service).
1615 @item long int ru_nivcsw
1616 The number of times an involuntary context switch took place (because
1617 the time slice expired, or another process of higher priority became
1622 An additional historical function for examining usage figures,
1623 @code{vtimes}, is supported but not documented here. It is declared in
1624 @file{sys/vtimes.h}.
1626 @node Limits on Resources
1627 @section Limiting Resource Usage
1628 @cindex resource limits
1629 @cindex limits on resource usage
1630 @cindex usage limits
1632 You can specify limits for the resource usage of a process. When the
1633 process tries to exceed a limit, it may get a signal, or the system call
1634 by which it tried to do so may fail, depending on the limit. Each
1635 process initially inherits its limit values from its parent, but it can
1636 subsequently change them.
1638 @pindex sys/resource.h
1639 The symbols in this section are defined in @file{sys/resource.h}.
1641 @comment sys/resource.h
1643 @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
1644 Read the current value and the maximum value of resource @var{resource}
1645 and store them in @code{*@var{rlp}}.
1647 The return value is @code{0} on success and @code{-1} on failure. The
1648 only possible @code{errno} error condition is @code{EFAULT}.
1650 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1651 32 bits system this function is in fact @code{getrlimit64}. I.e., the
1652 LFS interface transparently replaces the old interface.
1655 @comment sys/resource.h
1657 @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
1658 This function is similar to the @code{getrlimit} but its second
1659 parameter is a pointer to a variable of type @code{struct rlimit64}
1660 which allows this function to read values which wouldn't fit in the
1661 member of a @code{struct rlimit}.
1663 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
1664 bits machine this function is available under the name @code{getrlimit}
1665 and so transparently replaces the old interface.
1668 @comment sys/resource.h
1670 @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
1671 Store the current value and the maximum value of resource @var{resource}
1672 in @code{*@var{rlp}}.
1674 The return value is @code{0} on success and @code{-1} on failure. The
1675 following @code{errno} error condition is possible:
1679 You tried to change the maximum permissible limit value,
1680 but you don't have privileges to do so.
1683 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1684 32 bits system this function is in fact @code{setrlimit64}. I.e., the
1685 LFS interface transparently replaces the old interface.
1688 @comment sys/resource.h
1690 @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
1691 This function is similar to the @code{setrlimit} but its second
1692 parameter is a pointer to a variable of type @code{struct rlimit64}
1693 which allows this function to set values which wouldn't fit in the
1694 member of a @code{struct rlimit}.
1696 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
1697 bits machine this function is available under the name @code{setrlimit}
1698 and so transparently replaces the old interface.
1701 @comment sys/resource.h
1703 @deftp {Data Type} {struct rlimit}
1704 This structure is used with @code{getrlimit} to receive limit values,
1705 and with @code{setrlimit} to specify limit values. It has two fields:
1708 @item rlim_t rlim_cur
1709 The current value of the limit in question.
1710 This is also called the ``soft limit''.
1713 @item rlim_t rlim_max
1714 The maximum permissible value of the limit in question. You cannot set
1715 the current value of the limit to a larger number than this maximum.
1716 Only the super user can change the maximum permissible value.
1717 This is also called the ``hard limit''.
1721 In @code{getrlimit}, the structure is an output; it receives the current
1722 values. In @code{setrlimit}, it specifies the new values.
1725 For the LFS functions a similar type is defined in @file{sys/resource.h}.
1727 @comment sys/resource.h
1729 @deftp {Data Type} {struct rlimit64}
1730 This structure is used with @code{getrlimit64} to receive limit values,
1731 and with @code{setrlimit64} to specify limit values. It has two fields:
1734 @item rlim64_t rlim_cur
1735 The current value of the limit in question.
1736 This is also called the ``soft limit''.
1738 @item rlim64_t rlim_max
1739 The maximum permissible value of the limit in question. You cannot set
1740 the current value of the limit to a larger number than this maximum.
1741 Only the super user can change the maximum permissible value.
1742 This is also called the ``hard limit''.
1745 In @code{getrlimit64}, the structure is an output; it receives the current
1746 values. In @code{setrlimit64}, it specifies the new values.
1749 Here is a list of resources that you can specify a limit for.
1750 Those that are sizes are measured in bytes.
1753 @comment sys/resource.h
1757 The maximum amount of cpu time the process can use. If it runs for
1758 longer than this, it gets a signal: @code{SIGXCPU}. The value is
1759 measured in seconds. @xref{Operation Error Signals}.
1761 @comment sys/resource.h
1764 @vindex RLIMIT_FSIZE
1765 The maximum size of file the process can create. Trying to write a
1766 larger file causes a signal: @code{SIGXFSZ}. @xref{Operation Error
1769 @comment sys/resource.h
1773 The maximum size of data memory for the process. If the process tries
1774 to allocate data memory beyond this amount, the allocation function
1777 @comment sys/resource.h
1780 @vindex RLIMIT_STACK
1781 The maximum stack size for the process. If the process tries to extend
1782 its stack past this size, it gets a @code{SIGSEGV} signal.
1783 @xref{Program Error Signals}.
1785 @comment sys/resource.h
1789 The maximum size core file that this process can create. If the process
1790 terminates and would dump a core file larger than this maximum size,
1791 then no core file is created. So setting this limit to zero prevents
1792 core files from ever being created.
1794 @comment sys/resource.h
1798 The maximum amount of physical memory that this process should get.
1799 This parameter is a guide for the system's scheduler and memory
1800 allocator; the system may give the process more memory when there is a
1803 @comment sys/resource.h
1805 @item RLIMIT_MEMLOCK
1806 The maximum amount of memory that can be locked into physical memory (so
1807 it will never be paged out).
1809 @comment sys/resource.h
1812 The maximum number of processes that can be created with the same user ID.
1813 If you have reached the limit for your user ID, @code{fork} will fail
1814 with @code{EAGAIN}. @xref{Creating a Process}.
1816 @comment sys/resource.h
1819 @vindex RLIMIT_NOFILE
1821 @vindex RLIMIT_OFILE
1822 The maximum number of files that the process can open. If it tries to
1823 open more files than this, it gets error code @code{EMFILE}.
1824 @xref{Error Codes}. Not all systems support this limit; GNU does, and
1827 @comment sys/resource.h
1830 @vindex RLIM_NLIMITS
1831 The number of different resource limits. Any valid @var{resource}
1832 operand must be less than @code{RLIM_NLIMITS}.
1835 @comment sys/resource.h
1837 @deftypevr Constant int RLIM_INFINITY
1838 This constant stands for a value of ``infinity'' when supplied as
1839 the limit value in @code{setrlimit}.
1842 @c ??? Someone want to finish these?
1843 Two historical functions for setting resource limits, @code{ulimit} and
1844 @code{vlimit}, are not documented here. The latter is declared in
1845 @file{sys/vlimit.h} and comes from BSD.
1848 @section Process Priority
1849 @cindex process priority
1850 @cindex priority of a process
1852 @pindex sys/resource.h
1853 When several processes try to run, their respective priorities determine
1854 what share of the CPU each process gets. This section describes how you
1855 can read and set the priority of a process. All these functions and
1856 macros are declared in @file{sys/resource.h}.
1858 The range of valid priority values depends on the operating system, but
1859 typically it runs from @code{-20} to @code{20}. A lower priority value
1860 means the process runs more often. These constants describe the range of
1864 @comment sys/resource.h
1868 The smallest valid priority value.
1870 @comment sys/resource.h
1874 The largest valid priority value.
1877 @comment sys/resource.h
1879 @deftypefun int getpriority (int @var{class}, int @var{id})
1880 Read the priority of a class of processes; @var{class} and @var{id}
1881 specify which ones (see below). If the processes specified do not all
1882 have the same priority, this returns the smallest value that any of them
1885 The return value is the priority value on success, and @code{-1} on
1886 failure. The following @code{errno} error condition are possible for
1891 The combination of @var{class} and @var{id} does not match any existing
1895 The value of @var{class} is not valid.
1898 When the return value is @code{-1}, it could indicate failure, or it
1899 could be the priority value. The only way to make certain is to set
1900 @code{errno = 0} before calling @code{getpriority}, then use @code{errno
1901 != 0} afterward as the criterion for failure.
1904 @comment sys/resource.h
1906 @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{priority})
1907 Set the priority of a class of processes to @var{priority}; @var{class}
1908 and @var{id} specify which ones (see below).
1910 The return value is @code{0} on success and @code{-1} on failure. The
1911 following @code{errno} error condition are defined for this function:
1915 The combination of @var{class} and @var{id} does not match any existing
1919 The value of @var{class} is not valid.
1922 You tried to set the priority of some other user's process, and you
1923 don't have privileges for that.
1926 You tried to lower the priority of a process, and you don't have
1927 privileges for that.
1931 The arguments @var{class} and @var{id} together specify a set of
1932 processes you are interested in. These are the possible values for
1936 @comment sys/resource.h
1939 @vindex PRIO_PROCESS
1940 Read or set the priority of one process. The argument @var{id} is a
1943 @comment sys/resource.h
1947 Read or set the priority of one process group. The argument @var{id} is
1950 @comment sys/resource.h
1954 Read or set the priority of one user's processes. The argument @var{id}
1958 If the argument @var{id} is 0, it stands for the current process,
1959 current process group, or the current user, according to @var{class}.
1961 @c ??? I don't know where we should say this comes from.
1964 @deftypefun int nice (int @var{increment})
1965 Increment the priority of the current process by @var{increment}.
1966 The return value is the same as for @code{setpriority}.
1968 Here is an equivalent definition for @code{nice}:
1972 nice (int increment)
1974 int old = getpriority (PRIO_PROCESS, 0);
1975 return setpriority (PRIO_PROCESS, 0, old + increment);