From 99a206167bd94400d129991e1ec257820eb6df00 Mon Sep 17 00:00:00 2001 From: Ulrich Drepper Date: Sun, 21 May 2000 21:22:28 +0000 Subject: Update. 2000-05-21 Ulrich Drepper * manual/memory.texi: Document memory handling functions. * manual/time.texi: Document timespec and friends. * manual/conf.texi: Fix references. * manual/ctype.texi: Likewise. * manual/errno.texi: Likewise. * manual/intro.texi: Likewise. * manual/locale.texi: Likewise. * manual/sysinfo.texi: Likewise. Patches by Bryan Henderson . --- ChangeLog | 12 + manual/conf.texi | 2 +- manual/ctype.texi | 2 +- manual/errno.texi | 2 +- manual/intro.texi | 9 +- manual/locale.texi | 6 +- manual/memory.texi | 729 ++++++++++++++++++++++++++++++++++++++++++++-------- manual/sysinfo.texi | 19 +- manual/time.texi | 704 +++++++++++++++++++++++++++++--------------------- 9 files changed, 1057 insertions(+), 428 deletions(-) diff --git a/ChangeLog b/ChangeLog index 2686f94..223904b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,15 @@ +2000-05-21 Ulrich Drepper + + * manual/memory.texi: Document memory handling functions. + * manual/time.texi: Document timespec and friends. + * manual/conf.texi: Fix references. + * manual/ctype.texi: Likewise. + * manual/errno.texi: Likewise. + * manual/intro.texi: Likewise. + * manual/locale.texi: Likewise. + * manual/sysinfo.texi: Likewise. + Patches by Bryan Henderson . + 2000-05-09 Jes Sorensen * sysdeps/ia64/dl-machine.h: Move DL_SYMBOL_ADDRESS definition to... diff --git a/manual/conf.texi b/manual/conf.texi index 9fdaa1c..7276984 100644 --- a/manual/conf.texi +++ b/manual/conf.texi @@ -366,7 +366,7 @@ Inquire about the parameter corresponding to @code{_POSIX_VERSION}. @comment POSIX.1 @item _SC_CLK_TCK Inquire about the parameter corresponding to @code{CLOCKS_PER_SEC}; -@pxref{Basic CPU Time}. +@pxref{CPU Time}. @comment unistd.h @comment GNU diff --git a/manual/ctype.texi b/manual/ctype.texi index 0d3ab60..dabb03a 100644 --- a/manual/ctype.texi +++ b/manual/ctype.texi @@ -1,4 +1,4 @@ -@node Character Handling, String and Array Utilities, Memory Allocation, Top +@node Character Handling, String and Array Utilities, Memory, Top @c %MENU% Character testing and conversion functions @chapter Character Handling diff --git a/manual/errno.texi b/manual/errno.texi index 49eb902..8b18c83 100644 --- a/manual/errno.texi +++ b/manual/errno.texi @@ -1,4 +1,4 @@ -@node Error Reporting, Memory Allocation, Introduction, Top +@node Error Reporting, Memory, Introduction, Top @chapter Error Reporting @c %MENU% How library functions report errors @cindex error reporting diff --git a/manual/intro.texi b/manual/intro.texi index b133560..e7318c2 100644 --- a/manual/intro.texi +++ b/manual/intro.texi @@ -572,10 +572,11 @@ debugging mechanism which allows you to put assertions in your code, and have diagnostic messages printed if the tests fail. @item -@ref{Memory Allocation}, describes the GNU library's facilities for -dynamic allocation of storage. If you do not know in advance how much -storage your program needs, you can allocate it dynamically instead, -and manipulate it via pointers. +@ref{Memory}, describes the GNU library's facilities for managing and +using virtual and real memory, including dynamic allocation of virtual +memory. If you do not know in advance how much memory your program +needs, you can allocate it dynamically instead, and manipulate it via +pointers. @item @ref{Character Handling}, contains information about character diff --git a/manual/locale.texi b/manual/locale.texi index 75564d9..6ca057a 100644 --- a/manual/locale.texi +++ b/manual/locale.texi @@ -57,7 +57,7 @@ The collating sequence for the local language and character set Formatting of numbers and currency amounts (@pxref{General Numeric}). @item -Formatting of dates and times (@pxref{Formatting Date and Time}). +Formatting of dates and times (@pxref{Formatting Calendar Time}). @item What language to use for output, including error messages @@ -157,7 +157,7 @@ monetary; see @ref{General Numeric}. @comment ISO @item LC_TIME This category applies to formatting date and time values; see -@ref{Formatting Date and Time}. +@ref{Formatting Calendar Time}. @comment locale.h @comment XOPEN @@ -351,7 +351,7 @@ what information is provided by the currently selected locale. This is how the locale model is meant to work normally. As an example take the @code{strftime} function, which is meant to nicely -format date and time information (@pxref{Formatting Date and Time}). +format date and time information (@pxref{Formatting Calendar Time}). Part of the standard information contained in the @code{LC_TIME} category is the names of the months. Instead of requiring the programmer to take care of providing the translations the diff --git a/manual/memory.texi b/manual/memory.texi index 40f0389..b0996a5 100644 --- a/manual/memory.texi +++ b/manual/memory.texi @@ -1,35 +1,167 @@ -@comment !!! describe mmap et al (here?) -@c !!! doc brk/sbrk - -@node Memory Allocation, Character Handling, Error Reporting, Top -@chapter Memory Allocation -@c %MENU% Allocating memory dynamically and manipulating it via pointers +@node Memory, Character Handling, Error Reporting, Top +@chapter Virtual Memory Allocation And Paging +@c %MENU% Allocating virtual memory and controlling paging @cindex memory allocation @cindex storage allocation -The GNU system provides several methods for allocating memory space -under explicit program control. They vary in generality and in -efficiency. +This chapter describes how processes manage and use memory in a system +that uses the GNU C library. + +The GNU C Library has several functions for dynamically allocating +virtual memory in various ways. They vary in generality and in +efficiency. The library also provides functions for controlling paging +and allocation of real memory. + + +@menu +* Memory Concepts:: An introduction to concepts and terminology. +* Memory Allocation:: Allocating storage for your program data +* Locking Pages:: Preventing page faults +* Resizing the Data Segment:: @code{brk}, @code{sbrk} +@end menu + +Memory mapped I/O is not discussed in this chapter. @xref{Memory-mapped I/O}. + + + +@node Memory Concepts +@section Process Memory Concepts + +One of the most basic resources a process has available to it is memory. +There are a lot of different ways systems organize memory, but in a +typical one, each process has one linear virtual address space, with +addresses running from zero to some huge maximum. It need not be +contiguous; i.e. not all of these addresses actually can be used to +store data. + +The virtual memory is divided into pages (4 kilobytes is typical). +Backing each page of virtual memory is a page of real memory (called a +@dfn{frame}) or some secondary storage, usually disk space. The disk +space might be swap space or just some ordinary disk file. Actually, a +page of all zeroes sometimes has nothing at all backing it -- there's +just a flag saying it is all zeroes. +@cindex page frame +@cindex frame, real memory +@cindex swap space +@cindex page, virtual memory + +The same frame of real memory or backing store can back multiple virtual +pages belonging to multiple processes. This is normally the case, for +example, with virtual memory occupied by GNU C library code. The same +real memory frame containing the @code{printf} function backs a virtual +memory page in each of the existing processes that has a @code{printf} +call in its program. + +In order for a program to access any part of a virtual page, the page +must at that moment be backed by (``connected to'') a real frame. But +because there is usually a lot more virtual memory than real memory, the +pages must move back and forth between real memory and backing store +regularly, coming into real memory when a process needs to access them +and then retreating to backing store when not needed anymore. This +movement is called @dfn{paging}. + +When a program attempts to access a page which is not at that moment +backed by real memory, this is known as a @dfn{page fault}. When a page +fault occurs, the kernel suspends the process, places the page into a +real page frame (this is called ``paging in'' or ``faulting in''), then +resumes the process so that from the process' point of view, the page +was in real memory all along. In fact, to the process, all pages always +seem to be in real memory. Except for one thing: the elapsed execution +time of an instruction that would normally be a few nanoseconds is +suddenly much, much, longer (because the kernel normally has to do I/O +to complete the page-in). For programs sensitive to that, the functions +described in @ref{Locking Pages} can control it. +@cindex page fault +@cindex paging + +Within each virtual address space, a process has to keep track of what +is at which addresses, and that process is called memory allocation. +Allocation usually brings to mind meting out scarce resources, but in +the case of virtual memory, that's not a major goal, because there is +generally much more of it than anyone needs. Memory allocation within a +process is mainly just a matter of making sure that the same byte of +memory isn't used to store two different things. + +Processes allocate memory in two major ways: by exec and +programmatically. Actually, forking is a third way, but it's not very +interesting. @xref{Creating a Process}. + +Exec is the operation of creating a virtual address space for a process, +loading its basic program into it, and executing the program. It is +done by the ``exec'' family of functions (e.g. @code{execl}). The +operation takes a program file (an executable), it allocates space to +load all the data in the executable, loads it, and transfers control to +it. That data is most notably the instructions of the program (the +@dfn{text}), but also literals and constants in the program and even +some variables: C variables with the static storage class (@pxref{Memory +Allocation and C}). +@cindex executable +@cindex literals +@cindex constants + +Once that program begins to execute, it uses programmatic allocation to +gain additional memory. In a C program with the GNU C library, there +are two kinds of programmatic allocation: automatic and dynamic. +@xref{Memory Allocation and C}. + +Memory-mapped I/O is another form of dynamic virtual memory allocation. +Mapping memory to a file means declaring that the contents of certain +range of a process' addresses shall be identical to the contents of a +specified regular file. The system makes the virtual memory initially +contain the contents of the file, and if you modify the memory, the +system writes the same modification to the file. Note that due to the +magic of virtual memory and page faults, there is no reason for the +system to do I/O to read the file, or allocate real memory for its +contents, until the program accesses the virtual memory. +@xref{Memory-mapped I/O}. +@cindex memory mapped I/O +@cindex memory mapped file +@cindex files, accessing + +Just as it programmatically allocates memory, the program can +programmatically deallocate (@dfn{free}) it. You can't free the memory +that was allocated by exec. When the program exits or execs, you might +say that all its memory gets freed, but since in both cases the address +space ceases to exist, the point is really moot. @xref{Program +Termination}. +@cindex execing a program +@cindex freeing memory +@cindex exiting a program + +A process' virtual address space is divided into segments. A segment is +a contiguous range of virtual addresses. Three important segments are: -@iftex @itemize @bullet -@item -The @code{malloc} facility allows fully general dynamic allocation. -@xref{Unconstrained Allocation}. -@item -Obstacks are another facility, less general than @code{malloc} but more -efficient and convenient for stacklike allocation. @xref{Obstacks}. +@item + +The @dfn{text segment} contains a program's instructions and literals and +static constants. It is allocated by exec and stays the same size for +the life of the virtual address space. @item -The function @code{alloca} lets you allocate storage dynamically that -will be freed automatically. @xref{Variable Size Automatic}. +The @dfn{data segment} is working storage for the program. It can be +preallocated and preloaded by exec and the process can extend or shrink +it by calling functions as described in @xref{Resizing the Data +Segment}. Its lower end is fixed. + +@item +The @dfn{stack segment} contains a program stack. It grows as the stack +grows, but doesn't shrink when the stack shrinks. + @end itemize -@end iftex + + + +@node Memory Allocation +@section Allocating Storage For a Program's Data + +This section covers how ordinary programs manage storage for their data, +including the famous @code{malloc} function and some fancier facilities +special the GNU C library and GNU Compiler. @menu -* Memory Concepts:: An introduction to concepts and terminology. -* Dynamic Allocation and C:: How to get different kinds of allocation in C. +* Memory Allocation and C:: How to get different kinds of allocation in C. * Unconstrained Allocation:: The @code{malloc} facility allows fully general dynamic allocation. * Allocation Debugging:: Finding memory leaks and not freed memory. @@ -40,44 +172,21 @@ will be freed automatically. @xref{Variable Size Automatic}. calling function returns. @end menu -@node Memory Concepts -@section Dynamic Memory Allocation Concepts -@cindex dynamic allocation -@cindex static allocation -@cindex automatic allocation - -@dfn{Dynamic memory allocation} is a technique in which programs -determine as they are running where to store some information. You need -dynamic allocation when the number of memory blocks you need, or how -long you continue to need them, depends on the data you are working on. -For example, you may need a block to store a line read from an input file; -since there is no limit to how long a line can be, you must allocate the -storage dynamically and make it dynamically larger as you read more of the -line. +@node Memory Allocation and C +@subsection Memory Allocation in C Programs -Or, you may need a block for each record or each definition in the input -data; since you can't know in advance how many there will be, you must -allocate a new block for each record or definition as you read it. - -When you use dynamic allocation, the allocation of a block of memory is an -action that the program requests explicitly. You call a function or macro -when you want to allocate space, and specify the size with an argument. If -you want to free the space, you do so by calling another function or macro. -You can do these things whenever you want, as often as you want. - -@node Dynamic Allocation and C -@section Dynamic Allocation and C - -The C language supports two kinds of memory allocation through the variables -in C programs: +The C language supports two kinds of memory allocation through the +variables in C programs: @itemize @bullet @item @dfn{Static allocation} is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program -is started, and is never freed. +is started (part of the exec operation), and is never freed. +@cindex static memory allocation +@cindex static storage class @item @dfn{Automatic allocation} happens when you declare an automatic @@ -85,18 +194,52 @@ variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited. +@cindex automatic memory allocation +@cindex automatic storage class -In GNU C, the length of the automatic storage can be an expression +In GNU C, the size of the automatic storage can be an expression that varies. In other C implementations, it must be a constant. @end itemize +A third important kind of memory allocation, @dfn{dynamic allocation}, +is not supported by C variables but is available via GNU C library +functions. +@cindex dynamic memory allocation + +@subsubsection Dynamic Memory Allocation +@cindex dynamic memory allocation + +@dfn{Dynamic memory allocation} is a technique in which programs +determine as they are running where to store some information. You need +dynamic allocation when the amount of memory you need, or how long you +continue to need it, depends on factors that are not known before the +program runs. + +For example, you may need a block to store a line read from an input +file; since there is no limit to how long a line can be, you must +allocate the memory dynamically and make it dynamically larger as you +read more of the line. + +Or, you may need a block for each record or each definition in the input +data; since you can't know in advance how many there will be, you must +allocate a new block for each record or definition as you read it. + +When you use dynamic allocation, the allocation of a block of memory is +an action that the program requests explicitly. You call a function or +macro when you want to allocate space, and specify the size with an +argument. If you want to free the space, you do so by calling another +function or macro. You can do these things whenever you want, as often +as you want. + Dynamic allocation is not supported by C variables; there is no storage class ``dynamic'', and there can never be a C variable whose value is -stored in dynamically allocated space. The only way to refer to -dynamically allocated space is through a pointer. Because it is less -convenient, and because the actual process of dynamic allocation -requires more computation time, programmers generally use dynamic -allocation only when neither static nor automatic allocation will serve. +stored in dynamically allocated space. The only way to get dynamically +allocated memory is via a system call (which is generally via a GNU C +library function call), and the only way to refer to dynamically +allocated space is through a pointer. Because it is less convenient, +and because the actual process of dynamic allocation requires more +computation time, programmers generally use dynamic allocation only when +neither static nor automatic allocation will serve. For example, if you want to allocate dynamically some space to hold a @code{struct foobar}, you cannot declare a variable of type @code{struct @@ -116,8 +259,8 @@ address of the space. Then you can use the operators @samp{*} and @end smallexample @node Unconstrained Allocation -@section Unconstrained Allocation -@cindex unconstrained storage allocation +@subsection Unconstrained Allocation +@cindex unconstrained memory allocation @cindex @code{malloc} function @cindex heap, dynamic allocation from @@ -150,7 +293,7 @@ any time (or never). @end menu @node Basic Allocation -@subsection Basic Storage Allocation +@subsubsection Basic Memory Allocation @cindex allocation of memory with @code{malloc} To allocate a block of memory, call @code{malloc}. The prototype for @@ -200,7 +343,7 @@ ptr = (char *) malloc (length + 1); @xref{Representation of Strings}, for more information about this. @node Malloc Examples -@subsection Examples of @code{malloc} +@subsubsection Examples of @code{malloc} If no more space is available, @code{malloc} returns a null pointer. You should check the value of @emph{every} call to @code{malloc}. It is @@ -253,7 +396,7 @@ discover you want it to be bigger, use @code{realloc} (@pxref{Changing Block Size}). @node Freeing after Malloc -@subsection Freeing Memory Allocated with @code{malloc} +@subsubsection Freeing Memory Allocated with @code{malloc} @cindex freeing memory allocated with @code{malloc} @cindex heap, freeing memory from @@ -265,7 +408,7 @@ The prototype for this function is in @file{stdlib.h}. @comment malloc.h stdlib.h @comment ISO @deftypefun void free (void *@var{ptr}) -The @code{free} function deallocates the block of storage pointed at +The @code{free} function deallocates the block of memory pointed at by @var{ptr}. @end deftypefun @@ -313,7 +456,7 @@ of the program's space is given back to the system when the process terminates. @node Changing Block Size -@subsection Changing the Size of a Block +@subsubsection Changing the Size of a Block @cindex changing the size of a block (@code{malloc}) Often you do not know for certain how big a block you will ultimately need @@ -379,7 +522,7 @@ If the new size you specify is the same as the old size, @code{realloc} is guaranteed to change nothing and return the same address that you gave. @node Allocating Cleared Space -@subsection Allocating Cleared Space +@subsubsection Allocating Cleared Space The function @code{calloc} allocates memory and clears it to zero. It is declared in @file{stdlib.h}. @@ -413,9 +556,12 @@ But in general, it is not guaranteed that @code{calloc} calls should always define @code{calloc}, too. @node Efficiency and Malloc -@subsection Efficiency Considerations for @code{malloc} +@subsubsection Efficiency Considerations for @code{malloc} @cindex efficiency and @code{malloc} + + + @ignore @c No longer true, see below instead. @@ -446,12 +592,12 @@ more time to minimize the wasted space. @end ignore -As opposed to other versions, the @code{malloc} in GNU libc does not -round up block sizes to powers of two, neither for large nor for small -sizes. Neighboring chunks can be coalesced on a @code{free} no matter -what their size is. This makes the implementation suitable for all -kinds of allocation patterns without generally incurring high memory -waste through fragmentation. +As opposed to other versions, the @code{malloc} in the GNU C Library +does not round up block sizes to powers of two, neither for large nor +for small sizes. Neighboring chunks can be coalesced on a @code{free} +no matter what their size is. This makes the implementation suitable +for all kinds of allocation patterns without generally incurring high +memory waste through fragmentation. Very large blocks (much larger than a page) are allocated with @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation. @@ -463,7 +609,7 @@ after calling @code{free} wastes memory. The size threshold for @code{mmap} can also be disabled completely. @node Aligned Memory Blocks -@subsection Allocating Aligned Memory Blocks +@subsubsection Allocating Aligned Memory Blocks @cindex page boundary @cindex alignment (with @code{malloc}) @@ -505,7 +651,7 @@ valloc (size_t size) @end deftypefun @node Malloc Tunable Parameters -@subsection Malloc Tunable Parameters +@subsubsection Malloc Tunable Parameters You can adjust some parameters for dynamic memory allocation with the @code{mallopt} function. This function is the general SVID/XPG @@ -541,12 +687,12 @@ to zero disables all use of @code{mmap}. @end deftypefun @node Heap Consistency Checking -@subsection Heap Consistency Checking +@subsubsection Heap Consistency Checking @cindex heap consistency checking @cindex consistency checking, of heap -You can ask @code{malloc} to check the consistency of dynamic storage by +You can ask @code{malloc} to check the consistency of dynamic memory by using the @code{mcheck} function. This function is a GNU extension, declared in @file{mcheck.h}. @pindex mcheck.h @@ -652,13 +798,13 @@ uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to recompile your application. @node Hooks for Malloc -@subsection Storage Allocation Hooks +@subsubsection Memory Allocation Hooks @cindex allocation hooks, for @code{malloc} The GNU C library lets you modify the behavior of @code{malloc}, @code{realloc}, and @code{free} by specifying appropriate hook functions. You can use these hooks to help you debug programs that use -dynamic storage allocation, for example. +dynamic memory allocation, for example. The hook variables are declared in @file{malloc.h}. @pindex malloc.h @@ -838,10 +984,10 @@ installing such hooks. @c It's not clear whether to document them. @node Statistics of Malloc -@subsection Statistics for Storage Allocation with @code{malloc} +@subsubsection Statistics for Memory Allocation with @code{malloc} @cindex allocation statistics -You can get information about dynamic storage allocation by calling the +You can get information about dynamic memory allocation by calling the @code{mallinfo} function. This function and its associated data type are declared in @file{malloc.h}; they are an extension of the standard SVID/XPG version. @@ -851,7 +997,7 @@ SVID/XPG version. @comment GNU @deftp {Data Type} {struct mallinfo} This structure type is used to return information about the dynamic -storage allocator. It contains the following members: +memory allocator. It contains the following members: @table @code @item int arena @@ -859,7 +1005,7 @@ This is the total size of memory allocated with @code{sbrk} by @code{malloc}, in bytes. @item int ordblks -This is the number of chunks not in use. (The storage allocator +This is the number of chunks not in use. (The memory allocator internally gets chunks of memory from the operating system, and then carves them up to satisfy individual @code{malloc} requests; see @ref{Efficiency and Malloc}.) @@ -888,7 +1034,8 @@ This is the total size of memory occupied by free (not in use) chunks. @item int keepcost This is the size of the top-most releasable chunk that normally -borders the end of the heap (i.e. the ``brk'' of the process). +borders the end of the heap (i.e. the high end of the virtual address +space's data segment). @end table @end deftp @@ -901,7 +1048,7 @@ in a structure of type @code{struct mallinfo}. @end deftypefun @node Summary of Malloc -@subsection Summary of @code{malloc}-Related Functions +@subsubsection Summary of @code{malloc}-Related Functions Here is a summary of the functions that work with @code{malloc}: @@ -956,7 +1103,7 @@ Return information about the current dynamic memory usage. @end table @node Allocation Debugging -@section Allocation Debugging +@subsection Allocation Debugging @cindex allocation debugging @cindex malloc debugger @@ -980,7 +1127,7 @@ penalties for the program if the debugging mode is not enabled. @end menu @node Tracing malloc -@subsection How to install the tracing functionality +@subsubsection How to install the tracing functionality @comment mcheck.h @comment GNU @@ -1021,7 +1168,7 @@ systems. The prototype can be found in @file{mcheck.h}. @end deftypefun @node Using the Memory Debugger -@subsection Example program excerpts +@subsubsection Example program excerpts Even though the tracing functionality does not influence the runtime behaviour of the program it is not a good idea to call @code{mtrace} in @@ -1066,7 +1213,7 @@ calls which are executed by constructors of the program or used libraries). @node Tips for the Memory Debugger -@subsection Some more or less clever ideas +@subsubsection Some more or less clever ideas You know the situation. The program is prepared for debugging and in all debugging sessions it runs well. But once it is started without @@ -1112,7 +1259,7 @@ the first signal but if there is a memory leak this will show up nevertheless. @node Interpreting the traces -@subsection Interpreting the traces +@subsubsection Interpreting the traces If you take a look at the output it will look similar to this: @@ -1204,7 +1351,7 @@ times without freeing this memory before the program terminates. Whether this is a real problem remains to be investigated. @node Obstacks -@section Obstacks +@subsection Obstacks @cindex obstacks An @dfn{obstack} is a pool of memory containing a stack of objects. You @@ -1238,7 +1385,7 @@ the padding needed to start each object on a suitable boundary. @end menu @node Creating Obstacks -@subsection Creating Obstacks +@subsubsection Creating Obstacks The utilities for manipulating obstacks are declared in the header file @file{obstack.h}. @@ -1279,7 +1426,7 @@ directly or indirectly. You must also supply a function to free a chunk. These matters are described in the following section. @node Preparing for Obstacks -@subsection Preparing for Using Obstacks +@subsubsection Preparing for Using Obstacks Each source file in which you plan to use the obstack functions must include the header file @file{obstack.h}, like this: @@ -1308,7 +1455,7 @@ the following pair of macro definitions: @end smallexample @noindent -Though the storage you get using obstacks really comes from @code{malloc}, +Though the memory you get using obstacks really comes from @code{malloc}, using obstacks is faster because @code{malloc} is called less often, for larger blocks of memory. @xref{Obstack Chunks}, for full details. @@ -1365,7 +1512,7 @@ obstack_alloc_failed_handler = &my_obstack_alloc_failed; @end defvar @node Allocation in an Obstack -@subsection Allocation in an Obstack +@subsubsection Allocation in an Obstack @cindex allocation (obstacks) The most direct way to allocate an object in an obstack is with @@ -1438,7 +1585,7 @@ Contrast this with the previous example of @code{savestring} using @code{malloc} (@pxref{Basic Allocation}). @node Freeing Obstack Objects -@subsection Freeing Objects in an Obstack +@subsubsection Freeing Objects in an Obstack @cindex freeing (obstacks) To free an object allocated in an obstack, use the function @@ -1456,7 +1603,7 @@ everything allocated in @var{obstack} since @var{object}. @end deftypefun Note that if @var{object} is a null pointer, the result is an -uninitialized obstack. To free all storage in an obstack but leave it +uninitialized obstack. To free all memory in an obstack but leave it valid for further allocation, call @code{obstack_free} with the address of the first object allocated on the obstack: @@ -1470,7 +1617,7 @@ frees the chunk (@pxref{Preparing for Obstacks}). Then other obstacks, or non-obstack allocation, can reuse the space of the chunk. @node Obstack Functions -@subsection Obstack Functions and Macros +@subsubsection Obstack Functions and Macros @cindex macros The interfaces for using obstacks may be defined either as functions or @@ -1526,11 +1673,11 @@ various language extensions in GNU C permit defining the macros so as to compute each argument only once. @node Growing Objects -@subsection Growing Objects +@subsubsection Growing Objects @cindex growing objects (in obstacks) @cindex changing the size of a block (obstacks) -Because storage in obstack chunks is used sequentially, it is possible to +Because memory in obstack chunks is used sequentially, it is possible to build up an object step by step, adding one or more bytes at a time to the end of the object. With this technique, you do not need to know how much data you will put in the object until you come to the end of it. We call @@ -1640,7 +1787,7 @@ the current object smaller. Just don't try to shrink it beyond zero length---there's no telling what will happen if you do that. @node Extra Fast Growing -@subsection Extra Fast Growing Objects +@subsubsection Extra Fast Growing Objects @cindex efficiency and obstacks The usual functions for growing objects incur overhead for checking @@ -1743,7 +1890,7 @@ add_string (struct obstack *obstack, const char *ptr, int len) @end smallexample @node Status of an Obstack -@subsection Status of an Obstack +@subsubsection Status of an Obstack @cindex obstack status @cindex status of obstack @@ -1785,7 +1932,7 @@ obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr}) @end deftypefun @node Obstacks Data Alignment -@subsection Alignment of Data in Obstacks +@subsubsection Alignment of Data in Obstacks @cindex alignment (in obstacks) Each obstack has an @dfn{alignment boundary}; each object allocated in @@ -1825,7 +1972,7 @@ This will finish a zero-length object and then do proper alignment for the next object. @node Obstack Chunks -@subsection Obstack Chunks +@subsubsection Obstack Chunks @cindex efficiency of chunks @cindex chunks @@ -1881,7 +2028,7 @@ if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size}) @end smallexample @node Summary of Obstacks -@subsection Summary of Obstack Functions +@subsubsection Summary of Obstack Functions Here is a summary of all the functions associated with obstacks. Each takes the address of an obstack (@code{struct obstack *}) as its first @@ -1962,7 +2109,7 @@ Address just after the end of the currently growing object. @end table @node Variable Size Automatic -@section Automatic Storage with Variable Size +@subsection Automatic Storage with Variable Size @cindex automatic freeing @cindex @code{alloca} function @cindex automatic storage with variable size @@ -1984,7 +2131,7 @@ a BSD extension. @comment GNU, BSD @deftypefun {void *} alloca (size_t @var{size}); The return value of @code{alloca} is the address of a block of @var{size} -bytes of storage, allocated in the stack frame of the calling function. +bytes of memory, allocated in the stack frame of the calling function. @end deftypefun Do not use @code{alloca} inside the arguments of a function call---you @@ -2005,7 +2152,7 @@ alloca (4), y)}. @end menu @node Alloca Example -@subsection @code{alloca} Example +@subsubsection @code{alloca} Example As an example of the use of @code{alloca}, here is a function that opens a file name made from concatenating two argument strings, and returns a @@ -2044,7 +2191,7 @@ As you can see, it is simpler with @code{alloca}. But @code{alloca} has other, more important advantages, and some disadvantages. @node Advantages of Alloca -@subsection Advantages of @code{alloca} +@subsubsection Advantages of @code{alloca} Here are the reasons why @code{alloca} may be preferable to @code{malloc}: @@ -2056,7 +2203,7 @@ open-coded by the GNU C compiler.) @item Since @code{alloca} does not have separate pools for different sizes of block, space used for any size block can be reused for any other size. -@code{alloca} does not cause storage fragmentation. +@code{alloca} does not cause memory fragmentation. @item @cindex longjmp @@ -2084,17 +2231,17 @@ open2 (char *str1, char *str2, int flags, int mode) @end smallexample @noindent -Because of the way @code{alloca} works, the storage it allocates is +Because of the way @code{alloca} works, the memory it allocates is freed even when an error occurs, with no special effort required. By contrast, the previous definition of @code{open2} (which uses -@code{malloc} and @code{free}) would develop a storage leak if it were +@code{malloc} and @code{free}) would develop a memory leak if it were changed in this way. Even if you are willing to make more changes to fix it, there is no easy way to do so. @end itemize @node Disadvantages of Alloca -@subsection Disadvantages of @code{alloca} +@subsubsection Disadvantages of @code{alloca} @cindex @code{alloca} disadvantages @cindex disadvantages of @code{alloca} @@ -2103,7 +2250,7 @@ These are the disadvantages of @code{alloca} in comparison with @itemize @bullet @item -If you try to allocate more storage than the machine can provide, you +If you try to allocate more memory than the machine can provide, you don't get a clean error message. Instead you get a fatal signal like the one you would get from an infinite recursion; probably a segmentation violation (@pxref{Program Error Signals}). @@ -2115,7 +2262,7 @@ is available for use on systems with this deficiency. @end itemize @node GNU C Variable-Size Arrays -@subsection GNU C Variable-Size Arrays +@subsubsection GNU C Variable-Size Arrays @cindex variable-sized arrays In GNU C, you can replace most uses of @code{alloca} with an array of @@ -2150,6 +2297,357 @@ within one function, exiting a scope in which a variable-sized array was declared frees all blocks allocated with @code{alloca} during the execution of that scope. + +@node Resizing the Data Segment +@section Resizing the Data Segment + +The symbols in this section are declared in @file{unistd.h}. + +You will not normally use the functions in this section, because the +functions described in @ref{Memory Allocation} are easier to use. Those +are interfaces to a GNU C Library memory allocator that uses the +functions below itself. The functions below are simple interfaces to +system calls. + +@comment unistd.h +@comment BSD +@deftypefun int brk (void *@var{addr}) + +@code{brk} sets the high end of the calling process' data segment to +@var{addr}. + +The address of the end of a segment is defined to be the address of the +last byte in the segment plus 1. + +The function has no effect if @var{addr} is lower than the low end of +the data segment. (This is considered success, by the way). + +The function fails if it would cause the data segment to overlap another +segment or exceed the process' data storage limit (@pxref{Limits on +Resources}). + +The function is named for a common historical case where data storage +and the stack are in the same segment. Data storage allocation grows +upward from the bottom of the segment while the stack grows downward +toward it from the top of the segment and the curtain between them is +called the @dfn{break}. + +The return value is zero on success. On failure, the return value is +@code{-1} and @code{errno} is set accordingly. The following @code{errno} +values are specific to this function: + +@table @code +@item ENOMEM +The request would cause the data segment to overlap another segment or +exceed the process' data storage limit. +@end table + +@c The Brk system call in Linux (as opposed to the GNU C Library function) +@c is considerably different. It always returns the new end of the data +@c segment, whether it succeeds or fails. The GNU C library Brk determines +@c it's a failure if and only if if the system call returns an address less +@c than the address requested. + +@end deftypefun + + +@comment unistd.h +@comment BSD +@deftypefun int sbrk (ptrdiff_t @var{delta}) +This function is the same as @code{brk} except that you specify the new +end of the data segment as an offset @var{delta} from the current end +and on success the return value is the address of the resulting end of +the data segment instead of zero. + +This means you can use @samp{sbrk(0)} to find out what the current end +of the data segment is. + +@end deftypefun + + + +@node Locking Pages +@section Locking Pages +@cindex locking pages +@cindex memory lock +@cindex paging + +You can tell the system to associate a particular virtual memory page +with a real page frame and keep it that way --- i.e. cause the page to +be paged in if it isn't already and mark it so it will never be paged +out and consequently will never cause a page fault. This is called +@dfn{locking} a page. + +The functions in this chapter lock and unlock the calling process' +pages. + +@menu +* Why Lock Pages:: Reasons to read this section. +* Locked Memory Details:: Everything you need to know locked + memory +* Page Lock Functions:: Here's how to do it. +@end menu + +@node Why Lock Pages +@subsection Why Lock Pages + +Because page faults cause paged out pages to be paged in transparently, +a process rarely needs to be concerned about locking pages. However, +there are two reasons people sometimes are: + +@itemize @bullet + +@item +Speed. A page fault is transparent only insofar as the process is not +sensitive to how long it takes to do a simple memory access. Time-critical +processes, especially realtime processes, may not be able to wait or +may not be able to tolerate variance in execution speed. +@cindex realtime processing +@cindex speed of execution + +A process that needs to lock pages for this reason probably also needs +priority among other processes for use of the CPU. @xref{Priority}. + +In some cases, the programmer knows better than the system's demand +paging allocator which pages should remain in real memory to optimize +system performance. In this case, locking pages can help. + +@item +Privacy. If you keep secrets in virtual memory and that virtual memory +gets paged out, that increases the chance that the secrets will get out. +If a password gets written out to disk swap space, for example, it might +still be there long after virtual and real memory have been wiped clean. + +@end itemize + +Be aware that when you lock a page, that's one fewer page frame that can +be used to back other virtual memory (by the same or other processes), +which can mean more page faults, which means the system runs more +slowly. In fact, if you lock enough memory, some programs may not be +able to run at all for lack of real memory. + +@node Locked Memory Details +@subsection Locked Memory Details + +A memory lock is associated with a virtual page, not a real frame. The +paging rule is: If a frame backs at least one locked page, don't page it +out. + +Memory locks do not stack. I.e. you can't lock a particular page twice +so that it has to be unlocked twice before it is truly unlocked. It is +either locked or it isn't. + +A memory lock persists until the process that owns the memory explicitly +unlocks it. (But process termination and exec cause the virtual memory +to cease to exist, which you might say means it isn't locked any more). + +Memory locks are not inherited by child processes. (But note that on a +modern Unix system, immediately after a fork, the parent's and the +child's virtual address space are backed by the same real page frames, +so the child enjoys the parent's locks). @xref{Creating a Process}. + +Because of its ability to impact other processes, only the superuser can +lock a page. Any process can unlock its own page. + +The system sets limits on the amount of memory a process can have locked +and the amount of real memory it can have dedicated to it. @xref{Limits +on Resources}. + +In Linux, locked pages aren't as locked as you might think. +Two virtual pages that are not shared memory can nonetheless be backed +by the same real frame. The kernel does this in the name of efficiency +when it knows both virtual pages contain identical data, and does it +even if one or both of the virtual pages are locked. + +But when a process modifies one of those pages, the kernel must get it a +separate frame and fill it with the page's data. This is known as a +@dfn{copy-on-write page fault}. It takes a small amount of time and in +a pathological case, getting that frame may require I/O. +@cindex copy-on-write page fault +@cindex page fault, copy-on-write + +To make sure this doesn't happen to your program, don't just lock the +pages. Write to them as well, unless you know you won't write to them +ever. And to make sure you have pre-allocated frames for your stack, +enter a scope that declares a C automatic variable larger than the +maximum stack size you will need, set it to something, then return from +its scope. + +@node Page Lock Functions +@subsection Functions To Lock And Unlock Pages + +The symbols in this section are declared in @file{sys/mman.h}. These +functions are defined by POSIX.1b, but their availability depends on +your kernel. If your kernel doesn't allow these functions, they exist +but always fail. They @emph{are} available with a Linux kernel. + +@strong{Portability Note:} POSIX.1b requires that when the @code{mlock} +and @code{munlock} functions are available, the file @file{unistd.h} +define the macro @code{_POSIX_MEMLOCK_RANGE} and the file +@code{limits.h} define the macro @code{PAGESIZE} to be the size of a +memory page in bytes. It requires that when the @code{mlockall} and +@code{munlockall} functions are available, the @file{unistd.h} file +define the macro @code{_POSIX_MEMLOCK}. The GNU C library conforms to +this requirement. + +@comment sys/mman.h +@comment POSIX.1b +@deftypefun int mlock (const void *@var{addr}, size_t @var{len}) + +@code{mlock} locks a range of the calling process' virtual pages. + +The range of memory starts at address @var{addr} and is @var{len} bytes +long. Actually, since you must lock whole pages, it is the range of +pages that include any part of the specified range. + +When the function returns successfully, each of those pages is backed by +(connected to) a real frame (is resident) and is marked to stay that +way. This means the function may cause page-ins and have to wait for +them. + +When the function fails, it does not affect the lock status of any +pages. + +The return value is zero if the function succeeds. Otherwise, it is +@code{-1} and @code{errno} is set accordingly. @code{errno} values +specific to this function are: + +@table @code +@item ENOMEM +@itemize @bullet +@item +At least some of the specified address range does not exist in the +calling process' virtual address space. +@item +The locking would cause the process to exceed its locked page limit. +@end itemize + +@item EPERM +The calling process is not superuser. + +@item EINVAL +@var{len} is not positive. + +@item ENOSYS +The kernel does not provide @code{mlock} capability. + +@end table + +You can lock @emph{all} a process' memory with @code{mlockall}. You +unlock memory with @code{munlock} or @code{munlockall}. + +To avoid all page faults in a C program, you have to use +@code{mlockall}, because some of the memory a program uses is hidden +from the C code, e.g. the stack and automatic variables, and you +wouldn't know what address to tell @code{mlock}. + +@end deftypefun + +@comment sys/mman.h +@comment POSIX.1b +@deftypefun int munlock (const void *@var{addr}, size_t @var{len}) + +@code{mlock} unlocks a range of the calling process' virtual pages. + +@code{munlock} is the inverse of @code{mlock} and functions completely +analogously to @code{mlock}, except that there is no @code{EPERM} +failure. + +@end deftypefun + +@comment sys/mman.h +@comment POSIX.1b +@deftypefun int mlockall (int @var{flags}) + +@code{mlockall} locks all the pages in a process' virtual memory address +space, and/or any that are added to it in the future. This includes the +pages of the code, data and stack segment, as well as shared libraries, +user space kernel data, shared memory, and memory mapped files. + +@var{flags} is a string of single bit flags represented by the following +macros. They tell @code{mlockall} which of its functions you want. All +other bits must be zero. + +@table @code + +@item MCL_CURRENT +Lock all pages which currently exist in the calling process' virtual +address space. + +@item MCL_FUTURE +Set a mode such that any pages added to the process' virtual address +space in the future will be locked from birth. This mode does not +affect future address spaces owned by the same process so exec, which +replaces a process' address space, wipes out @code{MCL_FUTURE}. +@xref{Executing a File}. + +@end table + +When the function returns successfully, and you specified +@code{MCL_CURRENT}, all of the process' pages are backed by (connected +to) real frames (they are resident) and are marked to stay that way. +This means the function may cause page-ins and have to wait for them. + +When the process is in @code{MCL_FUTURE} mode because it successfully +executed this function and specified @code{MCL_CURRENT}, any system call +by the process that requires space be added to its virtual address space +fails with @code{errno} = @code{ENOMEM} if locking the additional space +would cause the process to exceed its locked page limit. In the case +that the address space addition that can't be accomodated is stack +expansion, the stack expansion fails and the kernel sends a +@code{SIGSEGV} signal to the process. + +When the function fails, it does not affect the lock status of any pages +or the future locking mode. + +The return value is zero if the function succeeds. Otherwise, it is +@code{-1} and @code{errno} is set accordingly. @code{errno} values +specific to this function are: + +@table @code +@item ENOMEM +@itemize @bullet +@item +At least some of the specified address range does not exist in the +calling process' virtual address space. +@item +The locking would cause the process to exceed its locked page limit. +@end itemize + +@item EPERM +The calling process is not superuser. + +@item EINVAL +Undefined bits in @var{flags} are not zero. + +@item ENOSYS +The kernel does not provide @code{mlockall} capability. + +@end table + +You can lock just specific pages with @code{mlock}. You unlock pages +with @code{munlockall} and @code{munlock}. + +@end deftypefun + + +@comment sys/mman.h +@comment POSIX.1b +@deftypefun int munlockall (void) + +@code{munlockall} unlocks every page in the calling process' virtual +address space and turn off @code{MCL_FUTURE} future locking mode. + +The return value is zero if the function succeeds. Otherwise, it is +@code{-1} and @code{errno} is set accordingly. The only way this +function can fail is for generic reasons that all functions and system +calls can fail, so there are no specific @code{errno} values. + +@end deftypefun + + + + @ignore @c This was never actually implemented. -zw @node Relocating Allocator @@ -2237,6 +2735,9 @@ and does not modify @code{*@var{handleptr}}. @end deftypefun @end ignore + + + @ignore @comment No longer available... diff --git a/manual/sysinfo.texi b/manual/sysinfo.texi index 266ecfd..7cc43ec 100644 --- a/manual/sysinfo.texi +++ b/manual/sysinfo.texi @@ -11,9 +11,8 @@ can make changes. @menu * Host Identification:: Determining the name of the machine. -* Hardware/Software Type ID:: Determining the hardware type of the - machine and what operating system it is - running. +* Platform Type:: Determining operating system and basic + machine type * Filesystem Handling:: Controlling/querying mounts * System Parameters:: Getting and setting various system parameters @end menu @@ -216,8 +215,8 @@ each machine. @end table @end deftypefun -@node Hardware/Software Type ID -@section Hardware/Software Type Identification +@node Platform Type +@section Platform Type Identification You can use the @code{uname} function to find out some information about the type of computer your program is running on. This function and the @@ -308,7 +307,7 @@ possibility. @node Filesystem Handling -@section Controlling/querying mounts +@section Controlling and Querying Mounts All files are in filesystems, and before you can access any file, its filesystem must be mounted. Because of Unix's concept of @@ -337,10 +336,10 @@ gets stored. @menu * Mount Information:: What is or could be mounted? -* Mount/Unmount/Remount:: Controlling what is mounted and how +* Mount-Unmount-Remount:: Controlling what is mounted and how @end menu -@node Mount Information, Mount/Unmount/Remount, , Filesystem Handling +@node Mount Information, Mount-Unmount-Remount, , Filesystem Handling For some programs it is desirable and necessary to access information about whether a certain filesystem is mounted and, if it is, where, or @@ -756,7 +755,7 @@ without relying on facilities outside the kernel to keep @file{mtab} up to date. -@node Mount/Unmount/Remount, , Mount Information, Filesystem Handling +@node Mount-Unmount-Remount, , Mount Information, Filesystem Handling This section describes the functions for mounting, unmounting, and remounting filesystems. @@ -1187,7 +1186,7 @@ parameters are: @item @code{gethostname}, @code{sethostname} (@xref{Host Identification}.) @item -@code{uname} (@xref{Hardware/Software Type ID}.) +@code{uname} (@xref{Platform Type}.) @item @code{bdflush} @end itemize diff --git a/manual/time.texi b/manual/time.texi index 1a1cddd..154b667 100644 --- a/manual/time.texi +++ b/manual/time.texi @@ -3,106 +3,263 @@ @chapter Date and Time This chapter describes functions for manipulating dates and times, -including functions for determining what the current time is and -conversion between different time representations. - -The time functions fall into three main categories: - -@itemize @bullet -@item -Functions for measuring elapsed CPU time are discussed in @ref{Processor -Time}. - -@item -Functions for measuring absolute clock or calendar time are discussed in -@ref{Calendar Time}. - -@item -Functions for setting alarms and timers are discussed in @ref{Setting -an Alarm}. -@end itemize +including functions for determining what time it is and conversion +between different time representations. @menu -* Processor Time:: Measures processor time used by a program. +* Time Basics:: Concepts and definitions. +* Elapsed Time:: Data types to represent elapsed times +* Processor And CPU Time:: Time a program has spent executing. * Calendar Time:: Manipulation of ``real'' dates and times. * Setting an Alarm:: Sending a signal after a specified time. * Sleeping:: Waiting for a period of time. @end menu -For functions to examine and control a process' CPU time, see -@xref{Resource Usage And Limitation}. +@node Time Basics +@section Time Basics +@cindex time -@node Processor Time -@section Processor Time - -If you're trying to optimize your program or measure its efficiency, it's -very useful to be able to know how much @dfn{processor time} or @dfn{CPU -time} it has used at any given point. Processor time is different from -actual wall clock time because it doesn't include any time spent waiting -for I/O or when some other process is running. Processor time is -represented by the data type @code{clock_t}, and is given as a number of -@dfn{clock ticks} relative to an arbitrary base time marking the beginning -of a single program invocation. +Discussing time in a technical manual can be difficult because the word +``time'' in English refers to lots of different things. In this manual, +we use a rigorous terminology to avoid confusion, and the only thing we +use the simple word ``time'' for is to talk about the abstract concept. + +A @dfn{calendar time} is a point in the time continuum, for example +November 4, 1990 at 18:02.5 UTC. Sometimes this is called ``absolute +time''. +@cindex calendar time + +We don't speak of a ``date'', because that is inherent in a calendar +time. +@cindex date + +An @dfn{interval} is a contiguous part of the time continuum between two +calendar times, for example the hour between 9:00 and 10:00 on July 4, +1980. +@cindex interval + +An @dfn{elapsed time} is the length of an interval, for example, 35 +minutes. People sometimes sloppily use the word ``interval'' to refer +to the elapsed time of some interval. +@cindex elapsed time +@cindex time, elapsed + +An @dfn{amount of time} is a sum of elapsed times, which need not be of +any specific intervals. For example, the amount of time it takes to +read a book might be 9 hours, independently of when and in how many +sittings it is read. + +A @dfn{period} is the elapsed time of an interval between two events, +especially when they are part of a sequence of regularly repeating +events. +@cindex period of time + +@dfn{CPU time} is like calendar time, except that it is based on the +subset of the time continuum when a particular process is actively +using a CPU. CPU time is, therefore, relative to a process. @cindex CPU time + +@dfn{Processor time} is an amount of time that a CPU is in use. In +fact, it's a basic system resource, since there's a limit to how much +can exist in any given interval (that limit is the elapsed time of the +interval times the number of CPUs in the processor). People often call +this CPU time, but we reserve the latter term in this manual for the +definition above. @cindex processor time + +@node Elapsed Time +@section Elapsed Time +@cindex elapsed time + +One way to represent an elapsed time is with a simple arithmetic data +type, as with the following function to compute the elapsed time between +two calendar times. This function is declared in @file{time.h}. + +@comment time.h +@comment ISO +@deftypefun double difftime (time_t @var{time1}, time_t @var{time0}) +The @code{difftime} function returns the number of seconds of elapsed +time between calendar time @var{time1} and calendar time @var{time0}, as +a value of type @code{double}. The difference ignores leap seconds +unless leap second support is enabled. + +In the GNU system, you can simply subtract @code{time_t} values. But on +other systems, the @code{time_t} data type might use some other encoding +where subtraction doesn't work directly. +@end deftypefun + +The GNU C library provides two data types specifically for representing +an elapsed time. They are used by various GNU C library functions, and +you can use them for your own purposes too. They're exactly the same +except that one has a resolution in microseconds, and the other, newer +one, is in nanoseconds. + +@comment sys/time.h +@comment BSD +@deftp {Data Type} {struct timeval} +@cindex timeval +The @code{struct timeval} structure represents an elapsed time. It is +declared in @file{sys/time.h} and has the following members: + +@table @code +@item long int tv_sec +This represents the number of whole seconds of elapsed time. + +@item long int tv_usec +This is the rest of the elapsed time (a fraction of a second), +represented as the number of microseconds. It is always less than one +million. + +@end table +@end deftp + +@comment sys/time.h +@comment POSIX.1 +@deftp {Data Type} {struct timespec} +@cindex timespec +The @code{struct timespec} structure represents an elapsed time. It is +declared in @file{time.h} and has the following members: + +@table @code +@item long int tv_sec +This represents the number of whole seconds of elapsed time. + +@item long int tv_nsec +This is the rest of the elapsed time (a fraction of a second), +represented as the number of nanoseconds. It is always less than one +billion. + +@end table +@end deftp + +It is often necessary to subtract two values of type @w{@code{struct +timeval}} or @w{@code{struct timespec}}. Here is the best way to do +this. It works even on some peculiar operating systems where the +@code{tv_sec} member has an unsigned type. + +@smallexample +/* @r{Subtract the `struct timeval' values X and Y,} + @r{storing the result in RESULT.} + @r{Return 1 if the difference is negative, otherwise 0.} */ + +int +timeval_subtract (result, x, y) + struct timeval *result, *x, *y; +@{ + /* @r{Perform the carry for the later subtraction by updating @var{y}.} */ + if (x->tv_usec < y->tv_usec) @{ + int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; + y->tv_usec -= 1000000 * nsec; + y->tv_sec += nsec; + @} + if (x->tv_usec - y->tv_usec > 1000000) @{ + int nsec = (x->tv_usec - y->tv_usec) / 1000000; + y->tv_usec += 1000000 * nsec; + y->tv_sec -= nsec; + @} + + /* @r{Compute the time remaining to wait.} + @r{@code{tv_usec} is certainly positive.} */ + result->tv_sec = x->tv_sec - y->tv_sec; + result->tv_usec = x->tv_usec - y->tv_usec; + + /* @r{Return 1 if result is negative.} */ + return x->tv_sec < y->tv_sec; +@} +@end smallexample + +Common functions that use @code{struct timeval} are @code{gettimeofday} +and @code{settimeofday}. + + +There are no GNU C library functions specifically oriented toward +dealing with elapsed times, but the calendar time, processor time, and +alarm and sleeping functions have a lot to do with them. + + +@node Processor And CPU Time +@section Processor And CPU Time + +If you're trying to optimize your program or measure its efficiency, +it's very useful to know how much processor time it uses. For that, +calendar time and elapsed times are useless because a process may spend +time waiting for I/O or for other processes to use the CPU. However, +you can get the information with the functions in this section. + +CPU time (@pxref{Time Basics}) is represented by the data type +@code{clock_t}, which is a number of @dfn{clock ticks}. It gives the +total amount of time a process has actively used a CPU since some +arbitrary event. On the GNU system, that event is the creation of the +process. While arbitrary in general, the event is always the same event +for any particular process, so you can always measure how much time on +the CPU a particular computation takes by examinining the process' CPU +time before and after the computation. +@cindex CPU time @cindex clock ticks @cindex ticks, clock -@cindex time, elapsed CPU + +In the GNU system, @code{clock_t} is equivalent to @code{long int} and +@code{CLOCKS_PER_SEC} is an integer value. But in other systems, both +@code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer +or floating-point types. Casting CPU time values to @code{double}, as +in the example above, makes sure that operations such as arithmetic and +printing work properly and consistently no matter what the underlying +representation is. + +Note that the clock can wrap around. On a 32bit system with +@code{CLOCKS_PER_SEC} set to one million this function will return the +same value approximately every 72 minutes. + +For additional functions to examine a process' use of processor time, +and to control it, @xref{Resource Usage And Limitation}. + @menu -* Basic CPU Time:: The @code{clock} function. -* Detailed CPU Time:: The @code{times} function. +* CPU Time:: The @code{clock} function. +* Processor Time:: The @code{times} function. @end menu -@node Basic CPU Time -@subsection Basic CPU Time Inquiry +@node CPU Time +@subsection CPU Time Inquiry -To get the elapsed CPU time used by a process, you can use the -@code{clock} function. This facility is declared in the header file -@file{time.h}. +To get a process' CPU time, you can use the @code{clock} function. This +facility is declared in the header file @file{time.h}. @pindex time.h -In typical usage, you call the @code{clock} function at the beginning and -end of the interval you want to time, subtract the values, and then divide -by @code{CLOCKS_PER_SEC} (the number of clock ticks per second), like this: +In typical usage, you call the @code{clock} function at the beginning +and end of the interval you want to time, subtract the values, and then +divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second) +to get processor time, like this: @smallexample @group #include clock_t start, end; -double elapsed; +double cpu_time_used; start = clock(); @dots{} /* @r{Do the work.} */ end = clock(); -elapsed = ((double) (end - start)) / CLOCKS_PER_SEC; +cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; @end group @end smallexample +Do not use a single CPU time as an amount of time; it doesn't work that +way. Either do a subtraction as shown above or query processor time +directly. @xref{Processor Time}. + Different computers and operating systems vary wildly in how they keep -track of processor time. It's common for the internal processor clock -to have a resolution somewhere between hundredth and millionth of a +track of CPU time. It's common for the internal processor clock +to have a resolution somewhere between a hundredth and millionth of a second. -In the GNU system, @code{clock_t} is equivalent to @code{long int} and -@code{CLOCKS_PER_SEC} is an integer value. But in other systems, both -@code{clock_t} and the type of the macro @code{CLOCKS_PER_SEC} can be -either integer or floating-point types. Casting processor time values -to @code{double}, as in the example above, makes sure that operations -such as arithmetic and printing work properly and consistently no matter -what the underlying representation is. - -Note that the clock can wrap around. On a 32bit system with -@code{CLOCKS_PER_SEC} set to one million this function will return the -same value approximately every 72 minutes. - @comment time.h @comment ISO @deftypevr Macro int CLOCKS_PER_SEC The value of this macro is the number of clock ticks per second measured -by the @code{clock} function. POSIX requires that this value is one +by the @code{clock} function. POSIX requires that this value be one million independent of the actual resolution. @end deftypevr @@ -116,25 +273,27 @@ This is an obsolete name for @code{CLOCKS_PER_SEC}. @comment ISO @deftp {Data Type} clock_t This is the type of the value returned by the @code{clock} function. -Values of type @code{clock_t} are in units of clock ticks. +Values of type @code{clock_t} are numbers of clock ticks. @end deftp @comment time.h @comment ISO @deftypefun clock_t clock (void) -This function returns the elapsed processor time. The base time is -arbitrary but doesn't change within a single process. If the processor +This function returns the calling process' current CPU time. If the CPU time is not available or cannot be represented, @code{clock} returns the value @code{(clock_t)(-1)}. @end deftypefun -@node Detailed CPU Time -@subsection Detailed Elapsed CPU Time Inquiry +@node Processor Time +@subsection Processor Time Inquiry -The @code{times} function returns more detailed information about -elapsed processor time in a @w{@code{struct tms}} object. You should +The @code{times} function returns information about a process' +consumption of processor time in a @w{@code{struct tms}} object, in +addition to the process' CPU time. @xref{Time Basics}. You should include the header file @file{sys/times.h} to use this facility. +@cindex processor time +@cindex CPU time @pindex sys/times.h @comment sys/times.h @@ -145,30 +304,33 @@ times. It contains at least the following members: @table @code @item clock_t tms_utime -This is the CPU time used in executing the instructions of the calling -process. +This is the total processor time the calling process has used in +executing the instructions of its program. @item clock_t tms_stime -This is the CPU time used by the system on behalf of the calling process. +This is the processor time the system has used on behalf of the calling +process. @item clock_t tms_cutime This is the sum of the @code{tms_utime} values and the @code{tms_cutime} values of all terminated child processes of the calling process, whose status has been reported to the parent process by @code{wait} or @code{waitpid}; see @ref{Process Completion}. In other words, it -represents the total CPU time used in executing the instructions of all -the terminated child processes of the calling process, excluding child -processes which have not yet been reported by @code{wait} or +represents the total processor time used in executing the instructions +of all the terminated child processes of the calling process, excluding +child processes which have not yet been reported by @code{wait} or @code{waitpid}. +@cindex child process @item clock_t tms_cstime -This is similar to @code{tms_cutime}, but represents the total CPU time -used by the system on behalf of all the terminated child processes of the -calling process. +This is similar to @code{tms_cutime}, but represents the total processor +time system has used on behalf of all the terminated child processes +of the calling process. @end table -All of the times are given in clock ticks. These are absolute values; in a -newly created process, they are all zero. @xref{Creating a Process}. +All of the times are given in numbers of clock ticks. Unlike CPU time, +these are the actual amounts of time; not relative to any event. +@xref{Creating a Process}. @end deftp @comment sys/times.h @@ -177,50 +339,46 @@ newly created process, they are all zero. @xref{Creating a Process}. The @code{times} function stores the processor time information for the calling process in @var{buffer}. -The return value is the same as the value of @code{clock()}: the elapsed -real time relative to an arbitrary base. The base is a constant within a -particular process, and typically represents the time since system -start-up. A value of @code{(clock_t)(-1)} is returned to indicate failure. +The return value is the calling process' CPU time (the same value you +get from @code{clock()}. @code{times} returns @code{(clock_t)(-1)} to +indicate failure. @end deftypefun @strong{Portability Note:} The @code{clock} function described in -@ref{Basic CPU Time}, is specified by the @w{ISO C} standard. The +@ref{CPU Time} is specified by the @w{ISO C} standard. The @code{times} function is a feature of POSIX.1. In the GNU system, the -value returned by the @code{clock} function is equivalent to the sum of -the @code{tms_utime} and @code{tms_stime} fields returned by -@code{times}. +CPU time is defined to be equivalent to the sum of the @code{tms_utime} +and @code{tms_stime} fields returned by @code{times}. @node Calendar Time @section Calendar Time -This section describes facilities for keeping track of points in time. -This is called calendar time and sometimes absolute time. -@cindex time, absolute -@cindex time, calendar -@cindex date and time +This section describes facilities for keeping track of calendar time. +@xref{Time Basics}. The GNU C library represents calendar time three ways: @itemize @bullet @item @dfn{Simple time} (the @code{time_t} data type) is a compact -representation, typically giving the number of seconds elapsed since -some implementation-specific base time. +representation, typically giving the number of seconds of elapsed time +since some implementation-specific base time. @cindex simple time @item -There is also a @dfn{high-resolution time} representation (the @code{struct -timeval} data type) that includes fractions of a second. Use this time -representation instead of simple time when you need greater -precision. +There is also a "high-resolution time" representation. Like simple +time, this represents a calendar time as an elapsed time since a base +time, but instead of measuring in whole seconds, it uses a @code{struct +timeval} data type, which includes fractions of a second. Use this time +representation instead of simple time when you need greater precision. @cindex high-resolution time @item @dfn{Local time} or @dfn{broken-down time} (the @code{struct tm} data -type) represents the date and time as a set of components specifying the +type) represents a calendar time as a set of components specifying the year, month, and so on in the Gregorian calendar, for a specific time -zone. This time representation is usually used only to communicate with -people. +zone. This calendar time representation is usually used only to +communicate with people. @cindex local time @cindex broken-down time @cindex Gregorian calendar @@ -232,7 +390,7 @@ people. * High-Resolution Calendar:: A time representation with greater precision. * Broken-down Time:: Facilities for manipulating local time. * High Accuracy Clock:: Maintaining a high accuracy system clock. -* Formatting Date and Time:: Converting times to strings. +* Formatting Calendar Time:: Converting times to strings. * Parsing Date and Time:: Convert textual time and date information back into broken-down time values. * TZ Variable:: How users specify the time zone. @@ -254,43 +412,34 @@ These facilities are declared in the header file @file{time.h}. @comment ISO @deftp {Data Type} time_t This is the data type used to represent simple time. Sometimes, it also -represents an elapsed time. -When interpreted as an absolute time -value, it represents the number of seconds elapsed since 00:00:00 on -January 1, 1970, Coordinated Universal Time. (This time is sometimes -referred to as the @dfn{epoch}.) POSIX requires that this count -not include leap seconds, but on some hosts this count includes leap seconds +represents an elapsed time. When interpreted as a calendar time value, +it represents the number of seconds elapsed since 00:00:00 on January 1, +1970, Coordinated Universal Time. (This calendar time is sometimes +referred to as the @dfn{epoch}.) POSIX requires that this count not +include leap seconds, but on some systems this count includes leap seconds if you set @code{TZ} to certain values (@pxref{TZ Variable}). -Note that a simple time has no concept of local time zone. Time @var{N} -is the same instant in time regardless of where on the globe the -computer is. +Note that a simple time has no concept of local time zone. Calendar +Time @var{T} is the same instant in time regardless of where on the +globe the computer is. In the GNU C library, @code{time_t} is equivalent to @code{long int}. In other systems, @code{time_t} might be either an integer or floating-point type. @end deftp -@comment time.h -@comment ISO -@deftypefun double difftime (time_t @var{time1}, time_t @var{time0}) -The @code{difftime} function returns the number of seconds elapsed -between time @var{time1} and time @var{time0}, as a value of type -@code{double}. The difference ignores leap seconds unless leap -second support is enabled. - -In the GNU system, you can simply subtract @code{time_t} values. But on -other systems, the @code{time_t} data type might use some other encoding -where subtraction doesn't work directly. -@end deftypefun +The function @code{difftime} tells you the elapsed time between two +simple calendar times, which is not always as easy to compute as just +subtracting. @xref{Elapsed Time}. @comment time.h @comment ISO @deftypefun time_t time (time_t *@var{result}) -The @code{time} function returns the current time as a value of type -@code{time_t}. If the argument @var{result} is not a null pointer, the -time value is also stored in @code{*@var{result}}. If the calendar -time is not available, the value @w{@code{(time_t)(-1)}} is returned. +The @code{time} function returns the current calendar time as a value of +type @code{time_t}. If the argument @var{result} is not a null pointer, +the calendar time value is also stored in @code{*@var{result}}. If the +current calendar time is not available, the value +@w{@code{(time_t)(-1)}} is returned. @end deftypefun @c The GNU C library implements stime() with a call to settimeofday() on @@ -299,7 +448,7 @@ time is not available, the value @w{@code{(time_t)(-1)}} is returned. @comment SVID, XPG @deftypefun int stime (time_t *@var{newtime}) @code{stime} sets the system clock, i.e. it tells the system that the -present absolute time is @var{newtime}, where @code{newtime} is +current calendar time is @var{newtime}, where @code{newtime} is interpreted as described in the above definition of @code{time_t}. @code{settimeofday} is a newer function which sets the system clock to @@ -333,27 +482,6 @@ declared in @file{sys/time.h}. @comment sys/time.h @comment BSD -@deftp {Data Type} {struct timeval} -The @code{struct timeval} structure represents a calendar time. It -has the following members: - -@table @code -@item long int tv_sec -This represents the number of seconds since the epoch. It is equivalent -to a normal @code{time_t} value. - -@item long int tv_usec -This is the fractional second value, represented as the number of -microseconds. - -Some times struct timeval values are used for time intervals. Then the -@code{tv_sec} member is the number of seconds in the interval, and -@code{tv_usec} is the number of additional microseconds. -@end table -@end deftp - -@comment sys/time.h -@comment BSD @deftp {Data Type} {struct timezone} The @code{struct timezone} structure is used to hold minimal information about the local time zone. It has the following members: @@ -370,49 +498,15 @@ The @code{struct timezone} type is obsolete and should never be used. Instead, use the facilities described in @ref{Time Zone Functions}. @end deftp -It is often necessary to subtract two values of type @w{@code{struct -timeval}}. Here is the best way to do this. It works even on some -peculiar operating systems where the @code{tv_sec} member has an -unsigned type. - -@smallexample -/* @r{Subtract the `struct timeval' values X and Y,} - @r{storing the result in RESULT.} - @r{Return 1 if the difference is negative, otherwise 0.} */ - -int -timeval_subtract (result, x, y) - struct timeval *result, *x, *y; -@{ - /* @r{Perform the carry for the later subtraction by updating @var{y}.} */ - if (x->tv_usec < y->tv_usec) @{ - int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; - y->tv_usec -= 1000000 * nsec; - y->tv_sec += nsec; - @} - if (x->tv_usec - y->tv_usec > 1000000) @{ - int nsec = (x->tv_usec - y->tv_usec) / 1000000; - y->tv_usec += 1000000 * nsec; - y->tv_sec -= nsec; - @} - - /* @r{Compute the time remaining to wait.} - @r{@code{tv_usec} is certainly positive.} */ - result->tv_sec = x->tv_sec - y->tv_sec; - result->tv_usec = x->tv_usec - y->tv_usec; - - /* @r{Return 1 if result is negative.} */ - return x->tv_sec < y->tv_sec; -@} -@end smallexample - @comment sys/time.h @comment BSD @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp}) -The @code{gettimeofday} function returns the current date and time in the -@code{struct timeval} structure indicated by @var{tp}. Information about the -time zone is returned in the structure pointed at @var{tzp}. If the @var{tzp} -argument is a null pointer, time zone information is ignored. +The @code{gettimeofday} function returns the current calendar time as +the elapsed time since the epoch in the @code{struct timeval} structure +indicated by @var{tp}. (@pxref{Elapsed Time} for a description of +@code{struct timespec}). Information about the time zone is returned in +the structure pointed at @var{tzp}. If the @var{tzp} argument is a null +pointer, time zone information is ignored. The return value is @code{0} on success and @code{-1} on failure. The following @code{errno} error condition is defined for this function: @@ -430,15 +524,17 @@ Instead, use the facilities described in @ref{Time Zone Functions}. @comment sys/time.h @comment BSD @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp}) -The @code{settimeofday} function sets the current date and time -according to the arguments. As for @code{gettimeofday}, time zone -information is ignored if @var{tzp} is a null pointer. +The @code{settimeofday} function sets the current calendar time in the +system clock according to the arguments. As for @code{gettimeofday}, +the calendar time is represented as the elapsed time since the epoch. +As for @code{gettimeofday}, time zone information is ignored if +@var{tzp} is a null pointer. You must be a privileged user in order to use @code{settimeofday}. Some kernels automatically set the system clock from some source such as a hardware clock when they start up. Others, including Linux, place the -system clock in an ``invalid'' state (in which attempts to read the time +system clock in an ``invalid'' state (in which attempts to read the clock fail). A call of @code{stime} removes the system clock from an invalid state, and system startup scripts typically run a program that calls @code{stime}. @@ -457,7 +553,7 @@ following @code{errno} error conditions are defined for this function: @table @code @item EPERM -This process cannot set the time because it is not privileged. +This process cannot set the clock because it is not privileged. @item ENOSYS The operating system does not support setting time zone information, and @@ -470,14 +566,14 @@ The operating system does not support setting time zone information, and @comment BSD @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta}) This function speeds up or slows down the system clock in order to make -gradual adjustments in the current time. This ensures that the time -reported by the system clock is always monotonically increasing, which -might not happen if you simply set the current time. +a gradual adjustment. This ensures that the calendar time reported by +the system clock is always monotonically increasing, which might not +happen if you simply set the clock. The @var{delta} argument specifies a relative adjustment to be made to -the current time. If negative, the system clock is slowed down for a -while until it has lost this much time. If positive, the system clock -is speeded up for a while. +the clock time. If negative, the system clock is slowed down for a +while until it has lost this much elapsed time. If positive, the system +clock is speeded up for a while. If the @var{olddelta} argument is not a null pointer, the @code{adjtime} function returns information about any previous time adjustment that @@ -520,15 +616,16 @@ This function is present only with a Linux kernel. @cindex broken-down time @cindex calendar time and broken-down time -Calendar time is represented as an amount of time since a fixed base -time. This is convenient for calculation, but has no relation to the -way people normally think of dates and times. By contrast, -@dfn{broken-down time} is a binary representation separated into year, -month, day, and so on. Broken-down time values are not useful for -calculations, but they are useful for printing human readable time. +Calendar time is represented by the usual GNU C library functions as an +elapsed time since a fixed base calendar time. This is convenient for +computation, but has no relation to the way people normally think of +calendar time. By contrast, @dfn{broken-down time} is a binary +representation of calendar time separated into year, month, day, and so +on. Broken-down time values are not useful for calculations, but they +are useful for printing human readable time information. A broken-down time value is always relative to a choice of time -zone, and it also indicates which time zone was used. +zone, and it also indicates which time zone that is. The symbols in this section are declared in the header file @file{time.h}. @@ -536,40 +633,44 @@ The symbols in this section are declared in the header file @file{time.h}. @comment ISO @deftp {Data Type} {struct tm} This is the data type used to represent a broken-down time. The structure -contains at least the following members, which can appear in any order: +contains at least the following members, which can appear in any order. @table @code @item int tm_sec -This is the number of seconds after the minute, normally in the range -@code{0} through @code{59}. (The actual upper limit is @code{60}, to allow -for leap seconds if leap second support is available.) +This is the number of full seconds since the top of the minute (normally +in the range @code{0} through @code{59}, but the actual upper limit is +@code{60}, to allow for leap seconds if leap second support is +available). @cindex leap second @item int tm_min -This is the number of minutes after the hour, in the range @code{0} through -@code{59}. +This is the number of full minutes since the top of the hour (in the +range @code{0} through @code{59}). @item int tm_hour -This is the number of hours past midnight, in the range @code{0} through -@code{23}. +This is the number of full hours past midnight (in the range @code{0} through +@code{23}). @item int tm_mday -This is the day of the month, in the range @code{1} through @code{31}. +This is the ordinal day of the month (in the range @code{1} through @code{31}). +Watch out for this one! As the only ordinal number in the structure, it is +inconsistent with the rest of the structure. @item int tm_mon -This is the number of months since January, in the range @code{0} through -@code{11}. +This is the number of full calendar months since the beginning of the +year (in the range @code{0} through @code{11}). Watch out for this one! +People usually use ordinal numbers for month-of-year (where January = 1). @item int tm_year -This is the number of years since @code{1900}. +This is the number of full calendar years since 1900. @item int tm_wday -This is the number of days since Sunday, in the range @code{0} through -@code{6}. +This is the number of full days since Sunday (in the range @code{0} through +@code{6}). @item int tm_yday -This is the number of days since January 1, in the range @code{0} through -@code{365}. +This is the number of full days since the beginning of the year (in the +range @code{0} through @code{365}). @item int tm_isdst @cindex Daylight Saving Time @@ -595,6 +696,7 @@ GNU extension, and is not visible in a strict @w{ISO C} environment. @end table @end deftp + @comment time.h @comment ISO @deftypefun {struct tm *} localtime (const time_t *@var{time}) @@ -738,12 +840,13 @@ These functions are declared in @file{sys/timex.h}. @tindex struct ntptimeval @deftp {Data Type} {struct ntptimeval} -This structure is used to monitor kernel time. It contains the -following members: +This structure is used for information about the system clock. It +contains the following members: @table @code @item struct timeval time -This is the current time. The @code{struct timeval} data type is -described in @ref{High-Resolution Calendar}. +This is the current calendar time, expressed as the elapsed time since +the epoch. The @code{struct timeval} data type is described in +@ref{Elapsed Time}. @item long int maxerror This is the maximum error, measured in microseconds. Unless updated @@ -753,7 +856,7 @@ platform-specific maximum value. @item long int esterror This is the estimated error, measured in microseconds. This value can be set by @code{ntp_adjtime} to indicate the estimated offset of the -local clock against the true time. +system clock from the true calendar time. @end table @end deftp @@ -788,18 +891,19 @@ symbolic constants have to be combined with @emph{binary or} to specify the effective mode. These constants start with @code{MOD_}. @item long int offset -This value indicates the current offset of the local clock from the true -time. The value is given in microseconds. If bit @code{MOD_OFFSET} is -set in @code{modes}, the offset (and possibly other dependent values) can -be set. The offset's absolute value must not exceed @code{MAXPHASE}. +This value indicates the current offset of the system clock from the true +calendar time. The value is given in microseconds. If bit +@code{MOD_OFFSET} is set in @code{modes}, the offset (and possibly other +dependent values) can be set. The offset's absolute value must not +exceed @code{MAXPHASE}. @item long int frequency -This value indicates the difference in frequency between the true time -and the local clock. The value is expressed as scaled PPM (parts per -million, 0.0001%). The scaling is @code{1 << SHIFT_USEC}. The value -can be set with bit @code{MOD_FREQUENCY}, but the absolute value must -not exceed @code{MAXFREQ}. +This value indicates the difference in frequency between the true +calendar time and the system clock. The value is expressed as scaled +PPM (parts per million, 0.0001%). The scaling is @code{1 << +SHIFT_USEC}. The value can be set with bit @code{MOD_FREQUENCY}, but +the absolute value must not exceed @code{MAXFREQ}. @item long int maxerror This is the maximum error, measured in microseconds. A new value can be @@ -832,17 +936,17 @@ scaled PPM. This value is used to increase the @code{maxerror} every second. @item struct timeval time -The current time. +The current calendar time. @item long int tick -The time between clock ticks in microseconds. A clock tick is a +The elapsed time between clock ticks in microseconds. A clock tick is a periodic timer interrupt on which the system clock is based. @item long int ppsfreq This is the first of a few optional variables that are present only if the system clock can use a PPS (pulse per second) signal to discipline -the local clock. The value is expressed in scaled PPM and it denotes -the difference in frequency between the local clock and the PPS signal. +the system clock. The value is expressed in scaled PPM and it denotes +the difference in frequency between the system clock and the PPS signal. @item long int jitter This value expresses a median filtered average of the PPS signal's @@ -920,11 +1024,11 @@ have this function but did have the synonymous @code{adjtimex}. @end deftypefun -@node Formatting Date and Time -@subsection Formatting Date and Time +@node Formatting Calendar Time +@subsection Formatting Calendar Time -The functions described in this section format time values as strings. -These functions are declared in the header file @file{time.h}. +The functions described in this section format calendar time values as +strings. These functions are declared in the header file @file{time.h}. @pindex time.h @comment time.h @@ -967,9 +1071,9 @@ return @code{NULL}. @comment time.h @comment ISO @deftypefun {char *} ctime (const time_t *@var{time}) -The @code{ctime} function is similar to @code{asctime}, except that the -time value is specified as a @code{time_t} simple time value rather -than in broken-down local time format. It is equivalent to +The @code{ctime} function is similar to @code{asctime}, except that you +specify the calendar time argument as a @code{time_t} simple time value +rather than in broken-down local time format. It is equivalent to @smallexample asctime (localtime (@var{time})) @@ -982,9 +1086,9 @@ does so. @xref{Time Zone Functions}. @comment time.h @comment POSIX.1c @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer}) -This function is similar to @code{ctime}, only that it places the result -in the string pointed to by @var{buffer}. It is equivalent to (written -using gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}): +This function is similar to @code{ctime}, but places the result in the +string pointed to by @var{buffer}. It is equivalent to (written using +gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}): @smallexample (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @}) @@ -1075,7 +1179,7 @@ The abbreviated month name according to the current locale. The full month name according to the current locale. @item %c -The preferred date and time representation for the current locale. +The preferred calendar time representation for the current locale. @item %C The century of the year. This is equivalent to the greatest integer not @@ -1178,7 +1282,7 @@ This format was introduced in @w{ISO C99} but was previously available as a GNU extension. @item %r -The complete time using the AM/PM format of the current locale. +The complete calendar time using the AM/PM format of the current locale. This format is a POSIX.2 extension and also appears in @w{ISO C99}. @@ -1203,7 +1307,7 @@ A single @samp{\t} (tabulator) character. This format is a POSIX.2 extension and also appears in @w{ISO C99}. @item %T -The time using decimal numbers using the format @code{%H:%M:%S}. +The time of day using decimal numbers using the format @code{%H:%M:%S}. This format is a POSIX.2 extension. @@ -1243,11 +1347,10 @@ the first week. All days preceding the first Monday in the year are considered to be in week @code{00}. @item %x -The preferred date representation for the current locale, but without the -time. +The preferred date representation for the current locale. @item %X -The preferred time representation for the current locale, but with no date. +The preferred time of day representation for the current locale. @item %y The year without a century as a decimal number (range @code{00} through @@ -1532,13 +1635,14 @@ Leap seconds are not counted unless leap second support is available. @code{%s} is a GNU extension following a GNU extension to @code{strftime}. @item %S -The seconds as a decimal number (range @code{0} through @code{61}). +The seconds as a decimal number (range @code{0} through @code{60}). Leading zeroes are permitted but not required. -Note the nonsense with @code{61}, as given in the Unix specification. -This is a result of a decision to allow double leap seconds. These do -not in fact exist but the myth persists. +@strong{Note:} The Unix specification says the upper bound on this value +is @code{61}, a result of a decision to allow double leap seconds. You +will not see the value @code{61} because no minute has more than one +leap second, but the myth persists. @item %OS Same as @code{%S} but using the locale's alternative numeric symbols. @@ -2135,7 +2239,7 @@ The time is 01:02 PM. @section Setting an Alarm The @code{alarm} and @code{setitimer} functions provide a mechanism for a -process to interrupt itself at some future time. They do this by setting a +process to interrupt itself in the future. They do this by setting a timer; when the timer expires, the process receives a signal. @cindex setting an alarm @@ -2146,21 +2250,21 @@ Each process has three independent interval timers available: @itemize @bullet @item -A real-time timer that counts clock time. This timer sends a +A real-time timer that counts elapsed time. This timer sends a @code{SIGALRM} signal to the process when it expires. @cindex real-time timer @cindex timer, real-time @item -A virtual timer that counts CPU time used by the process. This timer +A virtual timer that counts processor time used by the process. This timer sends a @code{SIGVTALRM} signal to the process when it expires. @cindex virtual timer @cindex timer, virtual @item -A profiling timer that counts both CPU time used by the process, and CPU -time spent in system calls on behalf of the process. This timer sends a -@code{SIGPROF} signal to the process when it expires. +A profiling timer that counts both processor time used by the process, +and processor time spent in system calls on behalf of the process. This +timer sends a @code{SIGPROF} signal to the process when it expires. @cindex profiling timer @cindex timer, profiling @@ -2195,16 +2299,15 @@ This structure is used to specify when a timer should expire. It contains the following members: @table @code @item struct timeval it_interval -This is the interval between successive timer interrupts. If zero, the +This is the period between successive timer interrupts. If zero, the alarm will only be sent once. @item struct timeval it_value -This is the interval to the first timer interrupt. If zero, the alarm is -disabled. +This is the period between now and the first timer interrupt. If zero, +the alarm is disabled. @end table -The @code{struct timeval} data type is described in @ref{High-Resolution -Calendar}. +The @code{struct timeval} data type is described in @ref{Elapsed Time}. @end deftp @comment sys/time.h @@ -2223,7 +2326,7 @@ following @code{errno} error conditions are defined for this function: @table @code @item EINVAL -The timer interval was too large. +The timer period is too large. @end table @end deftypefun @@ -2313,12 +2416,12 @@ specified by the POSIX.1 standard. @code{setitimer} is more powerful than @section Sleeping The function @code{sleep} gives a simple way to make the program wait -for short periods of time. If your program doesn't use signals (except -to terminate), then you can expect @code{sleep} to wait reliably for -the specified amount of time. Otherwise, @code{sleep} can return sooner -if a signal arrives; if you want to wait for a given period regardless -of signals, use @code{select} (@pxref{Waiting for I/O}) and don't -specify any descriptors to wait for. +for a short interval. If your program doesn't use signals (except to +terminate), then you can expect @code{sleep} to wait reliably throughout +the specified interval. Otherwise, @code{sleep} can return sooner if a +signal arrives; if you want to wait for a given interval regardless of +signals, use @code{select} (@pxref{Waiting for I/O}) and don't specify +any descriptors to wait for. @c !!! select can get EINTR; using SA_RESTART makes sleep win too. @comment unistd.h @@ -2327,9 +2430,9 @@ specify any descriptors to wait for. The @code{sleep} function waits for @var{seconds} or until a signal is delivered, whichever happens first. -If @code{sleep} function returns because the requested time has -elapsed, it returns a value of zero. If it returns because of delivery -of a signal, its return value is the remaining time in the sleep period. +If @code{sleep} function returns because the requested interval is over, +it returns a value of zero. If it returns because of delivery of a +signal, its return value is the remaining time in the sleep interval. The @code{sleep} function is declared in @file{unistd.h}. @end deftypefun @@ -2342,12 +2445,13 @@ eventual wakeup time to be off by an additional second or so. Suppose a few signals happen to arrive in rapid succession by bad luck---there is no limit on how much this could shorten or lengthen the wait. -Instead, compute the time at which the program should stop waiting, and -keep trying to wait until that time. This won't be off by more than a -second. With just a little more work, you can use @code{select} and -make the waiting period quite accurate. (Of course, heavy system load -can cause additional unavoidable delays---unless the machine is -dedicated to one application, there is no way you can avoid this.) +Instead, compute the calendar time at which the program should stop +waiting, and keep trying to wait until that calendar time. This won't +be off by more than a second. With just a little more work, you can use +@code{select} and make the waiting period quite accurate. (Of course, +heavy system load can cause additional unavoidable delays---unless the +machine is dedicated to one application, there is no way you can avoid +this.) On some systems, @code{sleep} can do strange things if your program uses @code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being @@ -2367,13 +2471,22 @@ the same program, because @code{sleep} does not work by means of @comment time.h @comment POSIX.1 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining}) -If resolution to seconds is not enough the @code{nanosleep} function -can be used. As the name suggests the sleeping period can be specified -in nanoseconds. The actual period of waiting time might be longer since -the requested time in the @var{requested_time} parameter is rounded up -to the next integer multiple of the actual resolution of the system. +If resolution to seconds is not enough the @code{nanosleep} function can +be used. As the name suggests the sleep interval can be specified in +nanoseconds. The actual elapsed time of the sleep interval might be +longer since the system rounds the elapsed time you request up to the +next integer multiple of the actual resolution the system can deliver. -If the function returns because the time has elapsed the return value is +*@code{requested_time} is the elapsed time of the interval you want to +sleep. + +The function returns as *@code{remaining} the elapsed time left in the +interval for which you requested to sleep. If the interval completed +without getting interrupted by a signal, this is zero. + +@code{struct timespec} is described in @xref{Elapsed Time}. + +If the function returns because the interval is over the return value is zero. If the function returns @math{-1} the global variable @var{errno} is set to the following values: @@ -2381,7 +2494,8 @@ is set to the following values: @item EINTR The call was interrupted because a signal was delivered to the thread. If the @var{remaining} parameter is not the null pointer the structure -pointed to by @var{remaining} is updated to contain the remaining time. +pointed to by @var{remaining} is updated to contain the remaining +elapsed time. @item EINVAL The nanosecond value in the @var{requested_time} parameter contains an @@ -2399,3 +2513,5 @@ be protected using cancellation handlers. The @code{nanosleep} function is declared in @file{time.h}. @end deftypefun + + -- cgit v1.1