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