From 7a68c94a5b8fb848590857f7d8c4a271bf4e8ea9 Mon Sep 17 00:00:00 2001 From: Ulrich Drepper Date: Mon, 13 Jul 1998 12:29:13 +0000 Subject: [PATCH] Update. 1998-07-10 18:14 -0400 Zack Weinberg * manual/Makefile: Overhauled. Generate libc.texinfo from the chapter files. Exorcise the chapters, chapters-incl mess. Support inserting doc chapters from add-on modules. (chapters): New variable. (add-chapters): New variable. (appendices): New variable. (libc.texinfo): New target. (clean): Fix bugs. (realclean): Fix bugs. * manual/texis.awk: New file. * manual/libc-texinfo.sh: New file. * manual/libc-texinfo.in: New file. * manual/conf.texi (top @node): Remove next pointer. * manual/lang.texi (top @node): Remove prev pointer. * manual/job.texi (top @node): Add explicit pointers. * manual/message.texi (top @node): Add explicit pointers. * manual/nss.texi (top @node): Add explicit pointers. * manual/process.texi (top @node): Add explicit pointers. * manual/startup.texi (top @node): Add explicit pointers. * manual/terminal.texi (top @node): Add explicit pointers. * manual/users.texi (top @node): Add explicit pointers. * manual/arith.texi: Add %MENU% tag. * manual/conf.texi: Add %MENU% tag. * manual/contrib.texi: Add %MENU% tag. * manual/ctype.texi: Add %MENU% tag. * manual/errno.texi: Add %MENU% tag. * manual/filesys.texi: Add %MENU% tag. * manual/header.texi: Add %MENU% tag. * manual/install.texi: Add %MENU% tag. * manual/intro.texi: Add %MENU% tag. * manual/io.texi: Add %MENU% tag. * manual/job.texi: Add %MENU% tag. * manual/lang.texi: Add %MENU% tag. * manual/llio.texi: Add %MENU% tag. * manual/locale.texi: Add %MENU% tag. * manual/maint.texi: Add %MENU% tag. * manual/math.texi: Add %MENU% tag. * manual/mbyte.texi: Add %MENU% tag. * manual/memory.texi: Add %MENU% tag. * manual/message.texi: Add %MENU% tag. * manual/nss.texi: Add %MENU% tag. * manual/pattern.texi: Add %MENU% tag. * manual/pipe.texi: Add %MENU% tag. * manual/process.texi: Add %MENU% tag. * manual/search.texi: Add %MENU% tag. * manual/setjmp.texi: Add %MENU% tag. * manual/signal.texi: Add %MENU% tag. * manual/socket.texi: Add %MENU% tag. * manual/startup.texi: Add %MENU% tag. * manual/stdio.texi: Add %MENU% tag. * manual/string.texi: Add %MENU% tag. * manual/sysinfo.texi: Add %MENU% tag. * manual/terminal.texi: Add %MENU% tag. * manual/time.texi: Add %MENU% tag. * manual/users.texi: Add %MENU% tag. 1998-07-13 Ulrich Drepper * sysdeps/unix/sysv/linux/i386/dl-procinfo.h (x86_cap_flags): Update. 1998-07-11 Andreas Jaeger * sysdeps/unix/sysv/linux/recvmsg.c (__libc_recvmsg): Use ANSI style declaration to avoid warning. * sysdeps/unix/sysv/linux/sendmsg.c (__libc_sendmsg): Likewise. 1998-07-04 Mark Kettenis * elf/rtld.c (process_dl_debug): Add missing continue. 1998-07-12 Mark Kettenis * elf/rtld.c (_dl_skip_args): Make global because the Hurd startup code needs it. 1998-07-10 Andreas Schwab * Makeconfig ($(common-objpfx)sysd-dirs): Write out definition of sysd-dirs-done. * Makerules: Don't generate version maps too early. ($(common-objpfx)sysd-versions): Force regeneration if the list of subdirs has changed. 1998-07-10 Andreas Schwab * elf/dlfcn.h (DL_CALL_FCT): Use portable comma expression. 1998-07-11 Andreas Schwab * iconv/gconv_db.c (gen_steps): Always set *handle and *nsteps. * iconv/gconv_dl.c (__gconv_find_shlib): Correct use of tfind return value. 1998-07-12 Andreas Schwab * elf/dl-open.c (dl_open_worker): New function. (_dl_open): Call it to do the actual work while catching errors. * elf/dl-close.c (_dl_close): Only call termination function if the initialisation function was called. 1998-07-13 Ulrich Drepper * libio/libioP.h (_IO_cleanup_registration_needed): Use __PMT. Reported by Felix von Leitner . 1998-07-13 10:28 Andreas Schwab * elf/rtld.c (process_dl_debug): Add missing continue. 1998-06-23 Mark Kettenis --- ChangeLog | 118 +- Makeconfig | 4 +- Makerules | 27 +- elf/dl-close.c | 4 +- elf/dl-open.c | 82 +- elf/dlfcn.h | 10 +- iconv/gconv_db.c | 6 + iconv/gconv_dl.c | 7 +- linuxthreads/linuxthreads.texi | 1427 ++++++++++++++++++++ manual/.cvsignore | 2 +- manual/Makefile | 88 +- manual/arith.texi | 1967 ++++++++++++++++++---------- manual/chapters.texi | 35 + manual/conf.texi | 4 +- manual/contrib.texi | 1 + manual/ctype.texi | 1 + manual/errno.texi | 1 + manual/filesys.texi | 1 + manual/header.texi | 1 + manual/install.texi | 1 + manual/intro.texi | 1 + manual/io.texi | 1 + manual/job.texi | 3 +- manual/lang.texi | 4 +- manual/libc-texinfo.sh | 115 ++ manual/libc.texinfo | 892 +------------ manual/llio.texi | 1 + manual/locale.texi | 1 + manual/maint.texi | 1 + manual/math.texi | 1395 +++++++------------- manual/mbyte.texi | 1 + manual/memory.texi | 1 + manual/message.texi | 3 +- manual/nss.texi | 7 +- manual/pattern.texi | 1 + manual/pipe.texi | 1 + manual/process.texi | 3 +- manual/search.texi | 1 + manual/setjmp.texi | 1 + manual/signal.texi | 1 + manual/socket.texi | 1 + manual/startup.texi | 3 +- manual/stdio.texi | 1 + manual/string.texi | 1 + manual/sysinfo.texi | 1 + manual/terminal.texi | 3 +- manual/texis | 78 ++ manual/texis.awk | 21 + manual/time.texi | 1 + manual/top-menu.texi | 499 +++++++ manual/users.texi | 3 +- sysdeps/unix/sysv/linux/i386/dl-procinfo.h | 4 +- sysdeps/unix/sysv/linux/recvmsg.c | 5 +- sysdeps/unix/sysv/linux/sendmsg.c | 5 +- 54 files changed, 4231 insertions(+), 2616 deletions(-) create mode 100644 linuxthreads/linuxthreads.texi create mode 100644 manual/chapters.texi create mode 100644 manual/libc-texinfo.sh create mode 100644 manual/texis create mode 100644 manual/texis.awk create mode 100644 manual/top-menu.texi diff --git a/ChangeLog b/ChangeLog index a94494b..d21c1f2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,116 @@ -Mon Jul 13 10:28:28 1998 Andreas Schwab +1998-07-10 18:14 -0400 Zack Weinberg + + * manual/Makefile: Overhauled. Generate libc.texinfo from the + chapter files. Exorcise the chapters, chapters-incl mess. + Support inserting doc chapters from add-on modules. + (chapters): New variable. + (add-chapters): New variable. + (appendices): New variable. + (libc.texinfo): New target. + (clean): Fix bugs. + (realclean): Fix bugs. + + * manual/texis.awk: New file. + * manual/libc-texinfo.sh: New file. + * manual/libc-texinfo.in: New file. + + * manual/conf.texi (top @node): Remove next pointer. + * manual/lang.texi (top @node): Remove prev pointer. + + * manual/job.texi (top @node): Add explicit pointers. + * manual/message.texi (top @node): Add explicit pointers. + * manual/nss.texi (top @node): Add explicit pointers. + * manual/process.texi (top @node): Add explicit pointers. + * manual/startup.texi (top @node): Add explicit pointers. + * manual/terminal.texi (top @node): Add explicit pointers. + * manual/users.texi (top @node): Add explicit pointers. + + * manual/arith.texi: Add %MENU% tag. + * manual/conf.texi: Add %MENU% tag. + * manual/contrib.texi: Add %MENU% tag. + * manual/ctype.texi: Add %MENU% tag. + * manual/errno.texi: Add %MENU% tag. + * manual/filesys.texi: Add %MENU% tag. + * manual/header.texi: Add %MENU% tag. + * manual/install.texi: Add %MENU% tag. + * manual/intro.texi: Add %MENU% tag. + * manual/io.texi: Add %MENU% tag. + * manual/job.texi: Add %MENU% tag. + * manual/lang.texi: Add %MENU% tag. + * manual/llio.texi: Add %MENU% tag. + * manual/locale.texi: Add %MENU% tag. + * manual/maint.texi: Add %MENU% tag. + * manual/math.texi: Add %MENU% tag. + * manual/mbyte.texi: Add %MENU% tag. + * manual/memory.texi: Add %MENU% tag. + * manual/message.texi: Add %MENU% tag. + * manual/nss.texi: Add %MENU% tag. + * manual/pattern.texi: Add %MENU% tag. + * manual/pipe.texi: Add %MENU% tag. + * manual/process.texi: Add %MENU% tag. + * manual/search.texi: Add %MENU% tag. + * manual/setjmp.texi: Add %MENU% tag. + * manual/signal.texi: Add %MENU% tag. + * manual/socket.texi: Add %MENU% tag. + * manual/startup.texi: Add %MENU% tag. + * manual/stdio.texi: Add %MENU% tag. + * manual/string.texi: Add %MENU% tag. + * manual/sysinfo.texi: Add %MENU% tag. + * manual/terminal.texi: Add %MENU% tag. + * manual/time.texi: Add %MENU% tag. + * manual/users.texi: Add %MENU% tag. + +1998-07-13 Ulrich Drepper + + * sysdeps/unix/sysv/linux/i386/dl-procinfo.h (x86_cap_flags): + Update. + +1998-07-11 Andreas Jaeger + + * sysdeps/unix/sysv/linux/recvmsg.c (__libc_recvmsg): Use ANSI + style declaration to avoid warning. + * sysdeps/unix/sysv/linux/sendmsg.c (__libc_sendmsg): Likewise. + +1998-07-04 Mark Kettenis + + * elf/rtld.c (process_dl_debug): Add missing continue. + +1998-07-12 Mark Kettenis + + * elf/rtld.c (_dl_skip_args): Make global because the Hurd startup + code needs it. + +1998-07-10 Andreas Schwab + + * Makeconfig ($(common-objpfx)sysd-dirs): Write out definition of + sysd-dirs-done. + * Makerules: Don't generate version maps too early. + ($(common-objpfx)sysd-versions): Force regeneration if the list of + subdirs has changed. + +1998-07-10 Andreas Schwab + + * elf/dlfcn.h (DL_CALL_FCT): Use portable comma expression. + +1998-07-11 Andreas Schwab + + * iconv/gconv_db.c (gen_steps): Always set *handle and *nsteps. + * iconv/gconv_dl.c (__gconv_find_shlib): Correct use of tfind + return value. + +1998-07-12 Andreas Schwab + + * elf/dl-open.c (dl_open_worker): New function. + (_dl_open): Call it to do the actual work while catching errors. + * elf/dl-close.c (_dl_close): Only call termination function if + the initialisation function was called. + +1998-07-13 Ulrich Drepper + + * libio/libioP.h (_IO_cleanup_registration_needed): Use __PMT. + Reported by Felix von Leitner . + +1998-07-13 10:28 Andreas Schwab * sysdeps/unix/sysv/linux/m68k/dl-envvars.h: New file. @@ -857,6 +969,10 @@ Mon Jul 13 10:28:28 1998 Andreas Schwab + * elf/rtld.c (process_dl_debug): Add missing continue. + +1998-06-23 Mark Kettenis + * elf/dl-load.c (_dl_map_object_from_fd): Add missing cast. 1998-06-23 Andreas Jaeger diff --git a/Makeconfig b/Makeconfig index ee1cc6e..43b44c9 100644 --- a/Makeconfig +++ b/Makeconfig @@ -777,7 +777,9 @@ all-Subdirs-files = $(wildcard $(addsuffix /Subdirs, $(config-sysdirs))) $(common-objpfx)sysd-dirs: $(common-objpfx)config.make $(all-Subdirs-files) (echo define sysdep-subdirs; \ sed 's/#.*$$//' $(all-Subdirs-files) /dev/null; \ - echo endef) > $@-tmp + echo endef; \ + echo 'sysd-dirs-done = t'; \ + ) > $@-tmp mv -f $@-tmp $@ endif # Makeconfig not yet included diff --git a/Makerules b/Makerules index dc5f25e..9bf62c6 100644 --- a/Makerules +++ b/Makerules @@ -276,22 +276,31 @@ ifndef sysd-rules-done no_deps=t endif -# Generate version maps. +# Generate version maps, but wait until sysdep-subdirs is known +ifdef sysd-dirs-done ifeq ($(versioning),yes) -ifndef no_deps -include $(common-objpfx)sysd-versions $(addprefix $(common-objpfx),$(version-maps)): $(common-objpfx)sysd-versions -generated += $(version-maps) +common-generated += $(version-maps) sysd-versions +ifndef avoid-generated +ifneq ($(sysd-versions-subdirs),$(all-subdirs) $(config-sysdirs)) +sysd-versions-force = FORCE +FORCE: +endif $(common-objpfx)sysd-versions: $(..)Versions.def $(..)scripts/versions.awk \ $(wildcard $(all-subdirs:%=$(..)%/Versions)) \ - $(wildcard $(+sysdep_dirs:%=%/Versions)) - $(AWK) -v buildroot=$(common-objpfx) -v defsfile=$< \ - -v move_if_change='$(move-if-change)' \ - -f $(filter-out $<,$^) > $@T + $(wildcard $(sysdirs:%=%/Versions)) \ + $(sysd-versions-force) + { echo 'sysd-versions-subdirs = $(all-subdirs) $(config-sysdirs)' ; \ + $(AWK) -v buildroot=$(common-objpfx) -v defsfile=$< \ + -v move_if_change='$(move-if-change)' \ + -f $(filter-out $< $(sysd-versions-force),$^); \ + } > $@T mv -f $@T $@ -endif -endif +endif # avoid-generated +endif # $(versioning) = yes +endif # sysd-dirs-done ifndef compile-command.S compile-command.S = $(compile.S) $(OUTPUT_OPTION) diff --git a/elf/dl-close.c b/elf/dl-close.c index 8b352d0..e1ca142 100644 --- a/elf/dl-close.c +++ b/elf/dl-close.c @@ -62,7 +62,9 @@ _dl_close (struct link_map *map) { struct link_map *imap = list[i]; if (imap->l_opencount == 1 && imap->l_type == lt_loaded - && imap->l_info[DT_FINI]) + && imap->l_info[DT_FINI] + /* Skip any half-cooked objects that were never initialized. */ + && imap->l_init_called) { /* When debugging print a message first. */ if (_dl_debug_impcalls) diff --git a/elf/dl-open.c b/elf/dl-open.c index 2b95909..b595f2d 100644 --- a/elf/dl-open.c +++ b/elf/dl-open.c @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -50,25 +51,31 @@ static size_t _dl_global_scope_alloc; __libc_lock_define_initialized_recursive (, _dl_load_lock) -struct link_map * -internal_function -_dl_open (const char *file, int mode) +/* We must be carefull not to leave us in an inconsistent state. Thus we + catch any error and re-raise it after cleaning up. */ + +struct dl_open_args { + const char *file; + int mode; + struct link_map *map; +}; + +static void +dl_open_worker (void *a) +{ + struct dl_open_args *args = a; + const char *file = args->file; + int mode = args->mode; struct link_map *new, *l; ElfW(Addr) init; struct r_debug *r; - /* Make sure we are alone. */ - __libc_lock_lock (_dl_load_lock); - /* Load the named object. */ - new = _dl_map_object (NULL, file, 0, lt_loaded, 0); + args->map = new = _dl_map_object (NULL, file, 0, lt_loaded, 0); if (new->l_searchlist) - { - /* It was already open. */ - __libc_lock_unlock (_dl_load_lock); - return new; - } + /* It was already open. */ + return; /* Load that object's dependencies. */ _dl_map_object_deps (new, NULL, 0, 0); @@ -147,7 +154,7 @@ _dl_open (const char *file, int mode) { _dl_global_scope = _dl_default_scope; nomem: - _dl_close (new); + new->l_global = 0; _dl_signal_error (ENOMEM, file, "cannot extend global scope"); } _dl_global_scope[2] = _dl_default_scope[2]; @@ -158,8 +165,8 @@ _dl_open (const char *file, int mode) } else { - if (_dl_global_scope_alloc < - (size_t) (_dl_global_scope_end - _dl_global_scope + 2)) + if (_dl_global_scope_end + 2 + == _dl_global_scope + _dl_global_scope_alloc) { /* Must extend the list. */ struct link_map **new = realloc (_dl_global_scope, @@ -167,9 +174,8 @@ _dl_open (const char *file, int mode) * sizeof (struct link_map *)); if (! new) goto nomem; - _dl_global_scope_end = new + (_dl_global_scope_end - - _dl_global_scope); _dl_global_scope = new; + _dl_global_scope_end = new + _dl_global_scope_alloc - 2; _dl_global_scope_alloc *= 2; } @@ -199,9 +205,49 @@ _dl_open (const char *file, int mode) /* We must be the static _dl_open in libc.a. A static program that has loaded a dynamic object now has competition. */ __libc_multiple_libcs = 1; +} + + +struct link_map * +internal_function +_dl_open (const char *file, int mode) +{ + struct dl_open_args args; + char *errstring; + int errcode; + + /* Make sure we are alone. */ + __libc_lock_lock (_dl_load_lock); + + args.file = file; + args.mode = mode; + args.map = NULL; + errcode = _dl_catch_error (&errstring, dl_open_worker, &args); /* Release the lock. */ __libc_lock_unlock (_dl_load_lock); - return new; + if (errstring) + { + /* Some error occured during loading. */ + char *local_errstring; + + /* Reset the global scope. */ + *_dl_global_scope_end = NULL; + + /* Remove the object from memory. It may be in an inconsistent + state if relocation failed, for example. */ + if (args.map) + _dl_close (args.map); + + /* Make a local copy of the error string so that we can release the + memory allocated for it. */ + local_errstring = strdupa (errstring); + free (errstring); + + /* Reraise the error. */ + _dl_signal_error (errcode, NULL, local_errstring); + } + + return args.map; } diff --git a/elf/dlfcn.h b/elf/dlfcn.h index 2f890bf..aa2e32f 100644 --- a/elf/dlfcn.h +++ b/elf/dlfcn.h @@ -81,14 +81,8 @@ extern int dladdr __P ((const void *__address, Dl_info *__info)); into foo = DL_CALL_FCT (fctp, (arg1, arg2)); */ -# if __GNUC__ >= 2 -# define DL_CALL_FCT(fctp, args) \ - (__extension__ ({ _dl_mcount_wrapper_check (fctp); \ - (*fctp) args; })) -# else -/* This feature is not available without GCC. */ -# define DL_CALL_FCT(fctp, args) (*fctp) args -# endif +# define DL_CALL_FCT(fctp, args) \ + (_dl_mcount_wrapper_check (fctp), (*(fctp)) args) /* This function calls the profiling functions. */ extern void _dl_mcount_wrapper_check __P ((void *__selfpc)); diff --git a/iconv/gconv_db.c b/iconv/gconv_db.c index 2c66249..d5d075d 100644 --- a/iconv/gconv_db.c +++ b/iconv/gconv_db.c @@ -239,6 +239,7 @@ gen_steps (struct derivation_step *best, const char *toset, } free (result); *nsteps = 0; + *handle = NULL; status = GCONV_NOCONV; } else @@ -247,6 +248,11 @@ gen_steps (struct derivation_step *best, const char *toset, status = GCONV_OK; } } + else + { + *nsteps = 0; + *handle = NULL; + } return status; } diff --git a/iconv/gconv_dl.c b/iconv/gconv_dl.c index 8375040..e0471b0 100644 --- a/iconv/gconv_dl.c +++ b/iconv/gconv_dl.c @@ -129,6 +129,7 @@ internal_function __gconv_find_shlib (const char *name) { struct gconv_loaded_object *found; + void *keyp; /* Search the tree of shared objects previously requested. Data in the tree are `loaded_object' structures, whose first member is a @@ -139,8 +140,8 @@ __gconv_find_shlib (const char *name) enough to a pointer to our structure to use as a lookup key that will be passed to `known_compare' (above). */ - found = __tfind (&name, &loaded, known_compare); - if (found == NULL) + keyp = __tfind (&name, &loaded, known_compare); + if (keyp == NULL) { /* This name was not known before. */ found = malloc (sizeof (struct gconv_loaded_object)); @@ -159,6 +160,8 @@ __gconv_find_shlib (const char *name) } } } + else + found = *(struct gconv_loaded_object **) keyp; /* Try to load the shared object if the usage count is 0. This implies that if the shared object is not loadable, the handle is diff --git a/linuxthreads/linuxthreads.texi b/linuxthreads/linuxthreads.texi new file mode 100644 index 0000000..dc1b146 --- /dev/null +++ b/linuxthreads/linuxthreads.texi @@ -0,0 +1,1427 @@ +@node POSIX Threads, , Top, Top +@chapter POSIX Threads +@c %MENU% The standard threads library + +@c This chapter needs more work bigtime. -zw + +This chapter describes the pthreads (POSIX threads) library. This +library provides support functions for multithreaded programs: thread +primitives, synchronization objects, and so forth. It also implements +POSIX 1003.1b semaphores (not to be confused with System V semaphores). + +The threads operations (@samp{pthread_*}) do not use @var{errno}. +Instead they return an error code directly. The semaphore operations do +use @var{errno}. + +@menu +* Basic Thread Operations:: Creating, terminating, and waiting for threads. +* Thread Attributes:: Tuning thread scheduling. +* Cancellation:: Stopping a thread before it's done. +* Cleanup Handlers:: Deallocating resources when a thread is + cancelled. +* Mutexes:: One way to synchronize threads. +* Condition Variables:: Another way. +* POSIX Semaphores:: And a third way. +* Thread-Specific Data:: Variables with different values in + different threads. +* Threads and Signal Handling:: Why you should avoid mixing the two, and + how to do it if you must. +* Miscellaneous Thread Functions:: A grab bag of utility routines. +@end menu + +@node Basic Thread Operations +@section Basic Thread Operations + +These functions are the thread equivalents of @code{fork}, @code{exit}, +and @code{wait}. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_create (pthread_t * @var{thread}, pthread_attr_t * @var{attr}, void * (*@var{start_routine})(void *), void * @var{arg}) +@code{pthread_create} creates a new thread of control that executes +concurrently with the calling thread. The new thread calls the +function @var{start_routine}, passing it @var{arg} as first argument. The +new thread terminates either explicitly, by calling @code{pthread_exit}, +or implicitly, by returning from the @var{start_routine} function. The +latter case is equivalent to calling @code{pthread_exit} with the result +returned by @var{start_routine} as exit code. + +The @var{attr} argument specifies thread attributes to be applied to the +new thread. @xref{Thread Attributes} for details. The @var{attr} +argument can also be @code{NULL}, in which case default attributes are +used: the created thread is joinable (not detached) and has an ordinary +(not realtime) scheduling policy. + +On success, the identifier of the newly created thread is stored in the +location pointed by the @var{thread} argument, and a 0 is returned. On +error, a non-zero error code is returned. + +This function may return the following errors: +@table @code +@item EAGAIN +Not enough system resources to create a process for the new thread, +or more than @code{PTHREAD_THREADS_MAX} threads are already active. +@end table +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun void pthread_exit (void *@var{retval}) +@code{pthread_exit} terminates the execution of the calling thread. All +cleanup handlers (@pxref{Cleanup Handlers}) that have been set for the +calling thread with @code{pthread_cleanup_push} are executed in reverse +order (the most recently pushed handler is executed first). Finalization +functions for thread-specific data are then called for all keys that +have non-@code{NULL} values associated with them in the calling thread +(@pxref{Thread-Specific Data}). Finally, execution of the calling +thread is stopped. + +The @var{retval} argument is the return value of the thread. It can be +retrieved from another thread using @code{pthread_join}. + +The @code{pthread_exit} function never returns. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cancel (pthread_t @var{thread}) + +@code{pthread_cancel} sends a cancellation request to the thread denoted +by the @var{thread} argument. If there is no such thread, +@code{pthread_cancel} fails and returns @code{ESRCH}. Otherwise it +returns 0. @xref{Cancellation}, for details. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_join (pthread_t @var{th}, void **thread_@var{return}) +@code{pthread_join} suspends the execution of the calling thread until +the thread identified by @var{th} terminates, either by calling +@code{pthread_exit} or by being cancelled. + +If @var{thread_return} is not @code{NULL}, the return value of @var{th} +is stored in the location pointed to by @var{thread_return}. The return +value of @var{th} is either the argument it gave to @code{pthread_exit}, +or @code{PTHREAD_CANCELED} if @var{th} was cancelled. + +The joined thread @code{th} must be in the joinable state: it must not +have been detached using @code{pthread_detach} or the +@code{PTHREAD_CREATE_DETACHED} attribute to @code{pthread_create}. + +When a joinable thread terminates, its memory resources (thread +descriptor and stack) are not deallocated until another thread performs +@code{pthread_join} on it. Therefore, @code{pthread_join} must be called +once for each joinable thread created to avoid memory leaks. + +At most one thread can wait for the termination of a given +thread. Calling @code{pthread_join} on a thread @var{th} on which +another thread is already waiting for termination returns an error. + +@code{pthread_join} is a cancellation point. If a thread is canceled +while suspended in @code{pthread_join}, the thread execution resumes +immediately and the cancellation is executed without waiting for the +@var{th} thread to terminate. If cancellation occurs during +@code{pthread_join}, the @var{th} thread remains not joined. + +On success, the return value of @var{th} is stored in the location +pointed to by @var{thread_return}, and 0 is returned. On error, one of +the following values is returned: +@table @code +@item ESRCH +No thread could be found corresponding to that specified by @var{th}. +@item EINVAL +The @var{th} thread has been detached, or another thread is already +waiting on termination of @var{th}. +@item EDEADLK +The @var{th} argument refers to the calling thread. +@end table +@end deftypefun + +@node Thread Attributes +@section Thread Attributes + +@comment pthread.h +@comment POSIX + +Threads have a number of attributes that may be set at creation time. +This is done by filling a thread attribute object @var{attr} of type +@code{pthread_attr_t}, then passing it as second argument to +@code{pthread_create}. Passing @code{NULL} is equivalent to passing a +thread attribute object with all attributes set to their default values. + +Attribute objects are consulted only when creating a new thread. The +same attribute object can be used for creating several threads. +Modifying an attribute object after a call to @code{pthread_create} does +not change the attributes of the thread previously created. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_attr_init (pthread_attr_t *@var{attr}) +@code{pthread_attr_init} initializes the thread attribute object +@var{attr} and fills it with default values for the attributes. (The +default values are listed below for each attribute.) + +Each attribute @var{attrname} (see below for a list of all attributes) +can be individually set using the function +@code{pthread_attr_set@var{attrname}} and retrieved using the function +@code{pthread_attr_get@var{attrname}}. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_attr_destroy (pthread_attr_t *@var{attr}) +@code{pthread_attr_destroy} destroys the attribute object pointed to by +@var{attr} releasing any resources associated with it. @var{attr} is +left in an undefined state, and you must not use it again in a call to +any pthreads function until it has been reinitialized. +@end deftypefun + +@findex pthread_attr_setinheritsched +@findex pthread_attr_setschedparam +@findex pthread_attr_setschedpolicy +@findex pthread_attr_setscope +@comment pthread.h +@comment POSIX +@deftypefun int pthread_attr_set@var{attr} (pthread_attr_t *@var{obj}, int @var{value}) +Set attribute @var{attr} to @var{value} in the attribute object pointed +to by @var{obj}. See below for a list of possible attributes and the +values they can take. + +On success, these functions return 0. If @var{value} is not meaningful +for the @var{attr} being modified, they will return the error code +@code{EINVAL}. Some of the functions have other failure modes; see +below. +@end deftypefun + +@findex pthread_attr_getinheritsched +@findex pthread_attr_getschedparam +@findex pthread_attr_getschedpolicy +@findex pthread_attr_getscope +@comment pthread.h +@comment POSIX +@deftypefun int pthread_attr_get@var{attr} (const pthread_attr_t *@var{obj}, int *@var{value}) +Store the current setting of @var{attr} in @var{obj} into the variable +pointed to by @var{value}. + +These functions always return 0. +@end deftypefun + +The following thread attributes are supported: +@table @samp +@item detachstate +Choose whether the thread is created in the joinable state (value +@code{PTHREAD_CREATE_JOINABLE}) or in the detached state +(@code{PTHREAD_CREATE_DETACHED}). The default is +@code{PTHREAD_CREATE_JOINABLE}. + +In the joinable state, another thread can synchronize on the thread +termination and recover its termination code using @code{pthread_join}, +but some of the thread resources are kept allocated after the thread +terminates, and reclaimed only when another thread performs +@code{pthread_join} on that thread. + +In the detached state, the thread resources are immediately freed when +it terminates, but @code{pthread_join} cannot be used to synchronize on +the thread termination. + +A thread created in the joinable state can later be put in the detached +thread using @code{pthread_detach}. + +@item schedpolicy +Select the scheduling policy for the thread: one of @code{SCHED_OTHER} +(regular, non-realtime scheduling), @code{SCHED_RR} (realtime, +round-robin) or @code{SCHED_FIFO} (realtime, first-in first-out). +The default is @code{SCHED_OTHER}. +@c Not doc'd in our manual: FIXME. +@c See @code{sched_setpolicy} for more information on scheduling policies. + +The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO} +are available only to processes with superuser privileges. +@code{pthread_attr_setschedparam} will fail and return @code{ENOTSUP} if +you try to set a realtime policy when you are unprivileged. + +The scheduling policy of a thread can be changed after creation with +@code{pthread_setschedparam}. + +@item schedparam +Change the scheduling parameter (the scheduling priority) +for the thread. The default is 0. + +This attribute is not significant if the scheduling policy is +@code{SCHED_OTHER}; it only matters for the realtime policies +@code{SCHED_RR} and @code{SCHED_FIFO}. + +The scheduling priority of a thread can be changed after creation with +@code{pthread_setschedparam}. + +@item inheritsched +Choose whether the scheduling policy and scheduling parameter for the +newly created thread are determined by the values of the +@var{schedpolicy} and @var{schedparam} attributes (value +@code{PTHREAD_EXPLICIT_SCHED}) or are inherited from the parent thread +(value @code{PTHREAD_INHERIT_SCHED}). The default is +@code{PTHREAD_EXPLICIT_SCHED}. + +@item scope +Choose the scheduling contention scope for the created thread. The +default is @code{PTHREAD_SCOPE_SYSTEM}, meaning that the threads contend +for CPU time with all processes running on the machine. In particular, +thread priorities are interpreted relative to the priorities of all +other processes on the machine. The other possibility, +@code{PTHREAD_SCOPE_PROCESS}, means that scheduling contention occurs +only between the threads of the running process: thread priorities are +interpreted relative to the priorities of the other threads of the +process, regardless of the priorities of other processes. + +@code{PTHREAD_SCOPE_PROCESS} is not supported in LinuxThreads. If you +try to set the scope to this value @code{pthread_attr_setscope} will +fail and return @code{ENOTSUP}. +@end table + +@node Cancellation +@section Cancellation + +Cancellation is the mechanism by which a thread can terminate the +execution of another thread. More precisely, a thread can send a +cancellation request to another thread. Depending on its settings, the +target thread can then either ignore the request, honor it immediately, +or defer it till it reaches a cancellation point. When threads are +first created by @code{pthread_create}, they always defer cancellation +requests. + +When a thread eventually honors a cancellation request, it behaves as if +@code{pthread_exit(PTHREAD_CANCELED)} was called. All cleanup handlers +are executed in reverse order, finalization functions for +thread-specific data are called, and finally the thread stops executing. +If the cancelled thread was joinable, the return value +@code{PTHREAD_CANCELED} is provided to whichever thread calls +@var{pthread_join} on it. See @code{pthread_exit} for more information. + +Cancellation points are the points where the thread checks for pending +cancellation requests and performs them. The POSIX threads functions +@code{pthread_join}, @code{pthread_cond_wait}, +@code{pthread_cond_timedwait}, @code{pthread_testcancel}, +@code{sem_wait}, and @code{sigwait} are cancellation points. In +addition, these system calls are cancellation points: + +@multitable @columnfractions .33 .33 .33 +@item @t{accept} @tab @t{open} @tab @t{sendmsg} +@item @t{close} @tab @t{pause} @tab @t{sendto} +@item @t{connect} @tab @t{read} @tab @t{system} +@item @t{fcntl} @tab @t{recv} @tab @t{tcdrain} +@item @t{fsync} @tab @t{recvfrom} @tab @t{wait} +@item @t{lseek} @tab @t{recvmsg} @tab @t{waitpid} +@item @t{msync} @tab @t{send} @tab @t{write} +@item @t{nanosleep} +@end multitable + +@noindent +All library functions that call these functions (such as +@code{printf}) are also cancellation points. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_setcancelstate (int @var{state}, int *@var{oldstate}) +@code{pthread_setcancelstate} changes the cancellation state for the +calling thread -- that is, whether cancellation requests are ignored or +not. The @var{state} argument is the new cancellation state: either +@code{PTHREAD_CANCEL_ENABLE} to enable cancellation, or +@code{PTHREAD_CANCEL_DISABLE} to disable cancellation (cancellation +requests are ignored). + +If @var{oldstate} is not @code{NULL}, the previous cancellation state is +stored in the location pointed to by @var{oldstate}, and can thus be +restored later by another call to @code{pthread_setcancelstate}. + +If the @var{state} argument is not @code{PTHREAD_CANCEL_ENABLE} or +@code{PTHREAD_CANCEL_DISABLE}, @code{pthread_setcancelstate} fails and +returns @code{EINVAL}. Otherwise it returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_setcanceltype (int @var{type}, int *@var{oldtype}) +@code{pthread_setcanceltype} changes the type of responses to +cancellation requests for the calling thread: asynchronous (immediate) +or deferred. The @var{type} argument is the new cancellation type: +either @code{PTHREAD_CANCEL_ASYNCHRONOUS} to cancel the calling thread +as soon as the cancellation request is received, or +@code{PTHREAD_CANCEL_DEFERRED} to keep the cancellation request pending +until the next cancellation point. If @var{oldtype} is not @code{NULL}, +the previous cancellation state is stored in the location pointed to by +@var{oldtype}, and can thus be restored later by another call to +@code{pthread_setcanceltype}. + +If the @var{type} argument is not @code{PTHREAD_CANCEL_DEFERRED} or +@code{PTHREAD_CANCEL_ASYNCHRONOUS}, @code{pthread_setcanceltype} fails +and returns @code{EINVAL}. Otherwise it returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun void pthread_testcancel (@var{void}) +@code{pthread_testcancel} does nothing except testing for pending +cancellation and executing it. Its purpose is to introduce explicit +checks for cancellation in long sequences of code that do not call +cancellation point functions otherwise. +@end deftypefun + +@node Cleanup Handlers +@section Cleanup Handlers + +Cleanup handlers are functions that get called when a thread terminates, +either by calling @code{pthread_exit} or because of +cancellation. Cleanup handlers are installed and removed following a +stack-like discipline. + +The purpose of cleanup handlers is to free the resources that a thread +may hold at the time it terminates. In particular, if a thread exits or +is cancelled while it owns a locked mutex, the mutex will remain locked +forever and prevent other threads from executing normally. The best way +to avoid this is, just before locking the mutex, to install a cleanup +handler whose effect is to unlock the mutex. Cleanup handlers can be +used similarly to free blocks allocated with @code{malloc} or close file +descriptors on thread termination. + +Here is how to lock a mutex @var{mut} in such a way that it will be +unlocked if the thread is canceled while @var{mut} is locked: + +@smallexample +pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut); +pthread_mutex_lock(&mut); +/* do some work */ +pthread_mutex_unlock(&mut); +pthread_cleanup_pop(0); +@end smallexample + +Equivalently, the last two lines can be replaced by + +@smallexample +pthread_cleanup_pop(1); +@end smallexample + +Notice that the code above is safe only in deferred cancellation mode +(see @code{pthread_setcanceltype}). In asynchronous cancellation mode, a +cancellation can occur between @code{pthread_cleanup_push} and +@code{pthread_mutex_lock}, or between @code{pthread_mutex_unlock} and +@code{pthread_cleanup_pop}, resulting in both cases in the thread trying +to unlock a mutex not locked by the current thread. This is the main +reason why asynchronous cancellation is difficult to use. + +If the code above must also work in asynchronous cancellation mode, +then it must switch to deferred mode for locking and unlocking the +mutex: + +@smallexample +pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype); +pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut); +pthread_mutex_lock(&mut); +/* do some work */ +pthread_cleanup_pop(1); +pthread_setcanceltype(oldtype, NULL); +@end smallexample + +The code above can be rewritten in a more compact and efficient way, +using the non-portable functions @code{pthread_cleanup_push_defer_np} +and @code{pthread_cleanup_pop_restore_np}: + +@smallexample +pthread_cleanup_push_defer_np(pthread_mutex_unlock, (void *) &mut); +pthread_mutex_lock(&mut); +/* do some work */ +pthread_cleanup_pop_restore_np(1); +@end smallexample + +@comment pthread.h +@comment POSIX +@deftypefun void pthread_cleanup_push (void (*@var{routine}) (void *), void *@var{arg}) + +@code{pthread_cleanup_push} installs the @var{routine} function with +argument @var{arg} as a cleanup handler. From this point on to the +matching @code{pthread_cleanup_pop}, the function @var{routine} will be +called with arguments @var{arg} when the thread terminates, either +through @code{pthread_exit} or by cancellation. If several cleanup +handlers are active at that point, they are called in LIFO order: the +most recently installed handler is called first. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun void pthread_cleanup_pop (int @var{execute}) +@code{pthread_cleanup_pop} removes the most recently installed cleanup +handler. If the @var{execute} argument is not 0, it also executes the +handler, by calling the @var{routine} function with arguments +@var{arg}. If the @var{execute} argument is 0, the handler is only +removed but not executed. +@end deftypefun + +Matching pairs of @code{pthread_cleanup_push} and +@code{pthread_cleanup_pop} must occur in the same function, at the same +level of block nesting. Actually, @code{pthread_cleanup_push} and +@code{pthread_cleanup_pop} are macros, and the expansion of +@code{pthread_cleanup_push} introduces an open brace @code{@{} with the +matching closing brace @code{@}} being introduced by the expansion of the +matching @code{pthread_cleanup_pop}. + +@comment pthread.h +@comment GNU +@deftypefun void pthread_cleanup_push_defer_np (void (*@var{routine}) (void *), void *@var{arg}) +@code{pthread_cleanup_push_defer_np} is a non-portable extension that +combines @code{pthread_cleanup_push} and @code{pthread_setcanceltype}. +It pushes a cleanup handler just as @code{pthread_cleanup_push} does, +but also saves the current cancellation type and sets it to deferred +cancellation. This ensures that the cleanup mechanism is effective even +if the thread was initially in asynchronous cancellation mode. +@end deftypefun + +@comment pthread.h +@comment GNU +@deftypefun void pthread_cleanup_pop_restore_np (int @var{execute}) +@code{pthread_cleanup_pop_restore_np} pops a cleanup handler introduced +by @code{pthread_cleanup_push_defer_np}, and restores the cancellation +type to its value at the time @code{pthread_cleanup_push_defer_np} was +called. +@end deftypefun + +@code{pthread_cleanup_push_defer_np} and +@code{pthread_cleanup_pop_restore_np} must occur in matching pairs, at +the same level of block nesting. + +The sequence + +@smallexample +pthread_cleanup_push_defer_np(routine, arg); +... +pthread_cleanup_pop_defer_np(execute); +@end smallexample + +@noindent +is functionally equivalent to (but more compact and efficient than) + +@smallexample +@{ + int oldtype; + pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype); + pthread_cleanup_push(routine, arg); + ... + pthread_cleanup_pop(execute); + pthread_setcanceltype(oldtype, NULL); +@} +@end smallexample + + +@node Mutexes +@section Mutexes + +A mutex is a MUTual EXclusion device, and is useful for protecting +shared data structures from concurrent modifications, and implementing +critical sections and monitors. + +A mutex has two possible states: unlocked (not owned by any thread), +and locked (owned by one thread). A mutex can never be owned by two +different threads simultaneously. A thread attempting to lock a mutex +that is already locked by another thread is suspended until the owning +thread unlocks the mutex first. + +None of the mutex functions is a cancellation point, not even +@code{pthread_mutex_lock}, in spite of the fact that it can suspend a +thread for arbitrary durations. This way, the status of mutexes at +cancellation points is predictable, allowing cancellation handlers to +unlock precisely those mutexes that need to be unlocked before the +thread stops executing. Consequently, threads using deferred +cancellation should never hold a mutex for extended periods of time. + +It is not safe to call mutex functions from a signal handler. In +particular, calling @code{pthread_mutex_lock} or +@code{pthread_mutex_unlock} from a signal handler may deadlock the +calling thread. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutex_init (pthread_mutex_t *@var{mutex}, const pthread_mutexattr_t *@var{mutexattr}) + +@code{pthread_mutex_init} initializes the mutex object pointed to by +@var{mutex} according to the mutex attributes specified in @var{mutexattr}. +If @var{mutexattr} is @code{NULL}, default attributes are used instead. + +The LinuxThreads implementation supports only one mutex attribute, +the @var{mutex kind}, which is either ``fast'', ``recursive'', or +``error checking''. The kind of a mutex determines whether +it can be locked again by a thread that already owns it. +The default kind is ``fast''. + +Variables of type @code{pthread_mutex_t} can also be initialized +statically, using the constants @code{PTHREAD_MUTEX_INITIALIZER} (for +fast mutexes), @code{PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP} (for +recursive mutexes), and @code{PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP} +(for error checking mutexes). + +@code{pthread_mutex_init} always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutex_lock (pthread_mutex_t *mutex)) +@code{pthread_mutex_lock} locks the given mutex. If the mutex is +currently unlocked, it becomes locked and owned by the calling thread, +and @code{pthread_mutex_lock} returns immediately. If the mutex is +already locked by another thread, @code{pthread_mutex_lock} suspends the +calling thread until the mutex is unlocked. + +If the mutex is already locked by the calling thread, the behavior of +@code{pthread_mutex_lock} depends on the kind of the mutex. If the mutex +is of the ``fast'' kind, the calling thread is suspended. It will +remain suspended forever, because no other thread can unlock the mutex. +If the mutex is of the ``error checking'' kind, @code{pthread_mutex_lock} +returns immediately with the error code @code{EDEADLK}. If the mutex is +of the ``recursive'' kind, @code{pthread_mutex_lock} succeeds and +returns immediately, recording the number of times the calling thread +has locked the mutex. An equal number of @code{pthread_mutex_unlock} +operations must be performed before the mutex returns to the unlocked +state. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutex_trylock (pthread_mutex_t *@var{mutex}) +@code{pthread_mutex_trylock} behaves identically to +@code{pthread_mutex_lock}, except that it does not block the calling +thread if the mutex is already locked by another thread (or by the +calling thread in the case of a ``fast'' mutex). Instead, +@code{pthread_mutex_trylock} returns immediately with the error code +@code{EBUSY}. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutex_unlock (pthread_mutex_t *@var{mutex}) +@code{pthread_mutex_unlock} unlocks the given mutex. The mutex is +assumed to be locked and owned by the calling thread on entrance to +@code{pthread_mutex_unlock}. If the mutex is of the ``fast'' kind, +@code{pthread_mutex_unlock} always returns it to the unlocked state. If +it is of the ``recursive'' kind, it decrements the locking count of the +mutex (number of @code{pthread_mutex_lock} operations performed on it by +the calling thread), and only when this count reaches zero is the mutex +actually unlocked. + +On ``error checking'' mutexes, @code{pthread_mutex_unlock} actually +checks at run-time that the mutex is locked on entrance, and that it was +locked by the same thread that is now calling +@code{pthread_mutex_unlock}. If these conditions are not met, +@code{pthread_mutex_unlock} returns @code{EPERM}, and the mutex remains +unchanged. ``Fast'' and ``recursive'' mutexes perform no such checks, +thus allowing a locked mutex to be unlocked by a thread other than its +owner. This is non-portable behavior and must not be relied upon. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutex_destroy (pthread_mutex_t *@var{mutex}) +@code{pthread_mutex_destroy} destroys a mutex object, freeing the +resources it might hold. The mutex must be unlocked on entrance. In the +LinuxThreads implementation, no resources are associated with mutex +objects, thus @code{pthread_mutex_destroy} actually does nothing except +checking that the mutex is unlocked. + +If the mutex is locked by some thread, @code{pthread_mutex_destroy} +returns @code{EBUSY}. Otherwise it returns 0. +@end deftypefun + +If any of the above functions (except @code{pthread_mutex_init}) +is applied to an uninitialized mutex, they will simply return +@code{EINVAL} and do nothing. + +A shared global variable @var{x} can be protected by a mutex as follows: + +@smallexample +int x; +pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; +@end smallexample + +All accesses and modifications to @var{x} should be bracketed by calls to +@code{pthread_mutex_lock} and @code{pthread_mutex_unlock} as follows: + +@smallexample +pthread_mutex_lock(&mut); +/* operate on x */ +pthread_mutex_unlock(&mut); +@end smallexample + +Mutex attributes can be specified at mutex creation time, by passing a +mutex attribute object as second argument to @code{pthread_mutex_init}. +Passing @code{NULL} is equivalent to passing a mutex attribute object +with all attributes set to their default values. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutexattr_init (pthread_mutexattr_t *@var{attr}) +@code{pthread_mutexattr_init} initializes the mutex attribute object +@var{attr} and fills it with default values for the attributes. + +This function always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_mutexattr_destroy (pthread_mutexattr_t *@var{attr}) +@code{pthread_mutexattr_destroy} destroys a mutex attribute object, +which must not be reused until it is +reinitialized. @code{pthread_mutexattr_destroy} does nothing in the +LinuxThreads implementation. + +This function always returns 0. +@end deftypefun + +LinuxThreads supports only one mutex attribute: the mutex kind, which is +either @code{PTHREAD_MUTEX_FAST_NP} for ``fast'' mutexes, +@code{PTHREAD_MUTEX_RECURSIVE_NP} for ``recursive'' mutexes, or +@code{PTHREAD_MUTEX_ERRORCHECK_NP} for ``error checking'' mutexes. As +the @code{NP} suffix indicates, this is a non-portable extension to the +POSIX standard and should not be employed in portable programs. + +The mutex kind determines what happens if a thread attempts to lock a +mutex it already owns with @code{pthread_mutex_lock}. If the mutex is of +the ``fast'' kind, @code{pthread_mutex_lock} simply suspends the calling +thread forever. If the mutex is of the ``error checking'' kind, +@code{pthread_mutex_lock} returns immediately with the error code +@code{EDEADLK}. If the mutex is of the ``recursive'' kind, the call to +@code{pthread_mutex_lock} returns immediately with a success return +code. The number of times the thread owning the mutex has locked it is +recorded in the mutex. The owning thread must call +@code{pthread_mutex_unlock} the same number of times before the mutex +returns to the unlocked state. + +The default mutex kind is ``fast'', that is, @code{PTHREAD_MUTEX_FAST_NP}. + +@comment pthread.h +@comment GNU +@deftypefun int pthread_mutexattr_setkind_np (pthread_mutexattr_t *@var{attr}, int @var{kind}) +@code{pthread_mutexattr_setkind_np} sets the mutex kind attribute in +@var{attr} to the value specified by @var{kind}. + +If @var{kind} is not @code{PTHREAD_MUTEX_FAST_NP}, +@code{PTHREAD_MUTEX_RECURSIVE_NP}, or +@code{PTHREAD_MUTEX_ERRORCHECK_NP}, this function will return +@code{EINVAL} and leave @var{attr} unchanged. +@end deftypefun + +@comment pthread.h +@comment GNU +@deftypefun int pthread_mutexattr_getkind_np (const pthread_mutexattr_t *@var{attr}, int *@var{kind}) +@code{pthread_mutexattr_getkind_np} retrieves the current value of the +mutex kind attribute in @var{attr} and stores it in the location pointed +to by @var{kind}. + +This function always returns 0. +@end deftypefun + +@node Condition Variables +@section Condition Variables + +A condition (short for ``condition variable'') is a synchronization +device that allows threads to suspend execution until some predicate on +shared data is satisfied. The basic operations on conditions are: signal +the condition (when the predicate becomes true), and wait for the +condition, suspending the thread execution until another thread signals +the condition. + +A condition variable must always be associated with a mutex, to avoid +the race condition where a thread prepares to wait on a condition +variable and another thread signals the condition just before the first +thread actually waits on it. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cond_init (pthread_cond_t *@var{cond}, pthread_condattr_t *cond_@var{attr}) + +@code{pthread_cond_init} initializes the condition variable @var{cond}, +using the condition attributes specified in @var{cond_attr}, or default +attributes if @var{cond_attr} is @code{NULL}. The LinuxThreads +implementation supports no attributes for conditions, hence the +@var{cond_attr} parameter is actually ignored. + +Variables of type @code{pthread_cond_t} can also be initialized +statically, using the constant @code{PTHREAD_COND_INITIALIZER}. + +This function always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cond_signal (pthread_cond_t *@var{cond}) +@code{pthread_cond_signal} restarts one of the threads that are waiting +on the condition variable @var{cond}. If no threads are waiting on +@var{cond}, nothing happens. If several threads are waiting on +@var{cond}, exactly one is restarted, but it is not specified which. + +This function always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cond_broadcast (pthread_cond_t *@var{cond}) +@code{pthread_cond_broadcast} restarts all the threads that are waiting +on the condition variable @var{cond}. Nothing happens if no threads are +waiting on @var{cond}. + +This function always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cond_wait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}) +@code{pthread_cond_wait} atomically unlocks the @var{mutex} (as per +@code{pthread_unlock_mutex}) and waits for the condition variable +@var{cond} to be signaled. The thread execution is suspended and does +not consume any CPU time until the condition variable is signaled. The +@var{mutex} must be locked by the calling thread on entrance to +@code{pthread_cond_wait}. Before returning to the calling thread, +@code{pthread_cond_wait} re-acquires @var{mutex} (as per +@code{pthread_lock_mutex}). + +Unlocking the mutex and suspending on the condition variable is done +atomically. Thus, if all threads always acquire the mutex before +signaling the condition, this guarantees that the condition cannot be +signaled (and thus ignored) between the time a thread locks the mutex +and the time it waits on the condition variable. + +This function always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cond_timedwait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime}) +@code{pthread_cond_timedwait} atomically unlocks @var{mutex} and waits +on @var{cond}, as @code{pthread_cond_wait} does, but it also bounds the +duration of the wait. If @var{cond} has not been signaled before time +@var{abstime}, the mutex @var{mutex} is re-acquired and +@code{pthread_cond_timedwait} returns the error code @code{ETIMEDOUT}. +The wait can also be interrupted by a signal; in that case +@code{pthread_cond_timedwait} returns @code{EINTR}. + +The @var{abstime} parameter specifies an absolute time, with the same +origin as @code{time} and @code{gettimeofday}: an @var{abstime} of 0 +corresponds to 00:00:00 GMT, January 1, 1970. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_cond_destroy (pthread_cond_t *@var{cond}) +@code{pthread_cond_destroy} destroys the condition variable @var{cond}, +freeing the resources it might hold. If any threads are waiting on the +condition variable, @code{pthread_cond_destroy} leaves @var{cond} +untouched and returns @code{EBUSY}. Otherwise it returns 0, and +@var{cond} must not be used again until it is reinitialized. + +In the LinuxThreads implementation, no resources are associated with +condition variables, so @code{pthread_cond_destroy} actually does +nothing. +@end deftypefun + +@code{pthread_cond_wait} and @code{pthread_cond_timedwait} are +cancellation points. If a thread is cancelled while suspended in one of +these functions, the thread immediately resumes execution, relocks the +mutex specified by @var{mutex}, and finally executes the cancellation. +Consequently, cleanup handlers are assured that @var{mutex} is locked +when they are called. + +It is not safe to call the condition variable functions from a signal +handler. In particular, calling @code{pthread_cond_signal} or +@code{pthread_cond_broadcast} from a signal handler may deadlock the +calling thread. + +Consider two shared variables @var{x} and @var{y}, protected by the +mutex @var{mut}, and a condition variable @var{cond} that is to be +signaled whenever @var{x} becomes greater than @var{y}. + +@smallexample +int x,y; +pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; +pthread_cond_t cond = PTHREAD_COND_INITIALIZER; +@end smallexample + +Waiting until @var{x} is greater than @var{y} is performed as follows: + +@smallexample +pthread_mutex_lock(&mut); +while (x <= y) @{ + pthread_cond_wait(&cond, &mut); +@} +/* operate on x and y */ +pthread_mutex_unlock(&mut); +@end smallexample + +Modifications on @var{x} and @var{y} that may cause @var{x} to become greater than +@var{y} should signal the condition if needed: + +@smallexample +pthread_mutex_lock(&mut); +/* modify x and y */ +if (x > y) pthread_mutex_broadcast(&cond); +pthread_mutex_unlock(&mut); +@end smallexample + +If it can be proved that at most one waiting thread needs to be waken +up (for instance, if there are only two threads communicating through +@var{x} and @var{y}), @code{pthread_cond_signal} can be used as a slightly more +efficient alternative to @code{pthread_cond_broadcast}. In doubt, use +@code{pthread_cond_broadcast}. + +To wait for @var{x} to becomes greater than @var{y} with a timeout of 5 +seconds, do: + +@smallexample +struct timeval now; +struct timespec timeout; +int retcode; + +pthread_mutex_lock(&mut); +gettimeofday(&now); +timeout.tv_sec = now.tv_sec + 5; +timeout.tv_nsec = now.tv_usec * 1000; +retcode = 0; +while (x <= y && retcode != ETIMEDOUT) @{ + retcode = pthread_cond_timedwait(&cond, &mut, &timeout); +@} +if (retcode == ETIMEDOUT) @{ + /* timeout occurred */ +@} else @{ + /* operate on x and y */ +@} +pthread_mutex_unlock(&mut); +@end smallexample + +Condition attributes can be specified at condition creation time, by +passing a condition attribute object as second argument to +@code{pthread_cond_init}. Passing @code{NULL} is equivalent to passing +a condition attribute object with all attributes set to their default +values. + +The LinuxThreads implementation supports no attributes for +conditions. The functions on condition attributes are included only for +compliance with the POSIX standard. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_condattr_init (pthread_condattr_t *@var{attr}) +@deftypefunx int pthread_condattr_destroy (pthread_condattr_t *@var{attr}) +@code{pthread_condattr_init} initializes the condition attribute object +@var{attr} and fills it with default values for the attributes. +@code{pthread_condattr_destroy} destroys the condition attribute object +@var{attr}. + +Both functions do nothing in the LinuxThreads implementation. + +@code{pthread_condattr_init} and @code{pthread_condattr_destroy} always +return 0. +@end deftypefun + +@node POSIX Semaphores +@section POSIX Semaphores + +@vindex SEM_VALUE_MAX +Semaphores are counters for resources shared between threads. The +basic operations on semaphores are: increment the counter atomically, +and wait until the counter is non-null and decrement it atomically. + +Semaphores have a maximum value past which they cannot be incremented. +The macro @code{SEM_VALUE_MAX} is defined to be this maximum value. In +the GNU C library, @code{SEM_VALUE_MAX} is equal to @code{INT_MAX} +(@pxref{Range of Type}), but it may be much smaller on other systems. + +The pthreads library implements POSIX 1003.1b semaphores. These should +not be confused with System V semaphores (@code{ipc}, @code{semctl} and +@code{semop}). +@c !!! SysV IPC is not doc'd at all in our manual + +All the semaphore functions and macros are defined in @file{semaphore.h}. + +@comment semaphore.h +@comment POSIX +@deftypefun int sem_init (sem_t *@var{sem}, int @var{pshared}, unsigned int @var{value}) +@code{sem_init} initializes the semaphore object pointed to by +@var{sem}. The count associated with the semaphore is set initially to +@var{value}. The @var{pshared} argument indicates whether the semaphore +is local to the current process (@var{pshared} is zero) or is to be +shared between several processes (@var{pshared} is not zero). + +On success @code{sem_init} returns 0. On failure it returns -1 and sets +@var{errno} to one of the following values: + +@table @code +@item EINVAL +@var{value} exceeds the maximal counter value @code{SEM_VALUE_MAX} + +@item ENOSYS +@var{pshared} is not zero. LinuxThreads currently does not support +process-shared semaphores. (This will eventually change.) +@end table +@end deftypefun + +@comment semaphore.h +@comment POSIX +@deftypefun int sem_destroy (sem_t * @var{sem}) +@code{sem_destroy} destroys a semaphore object, freeing the resources it +might hold. If any threads are waiting on the semaphore when +@code{sem_destroy} is called, it fails and sets @var{errno} to +@code{EBUSY}. + +In the LinuxThreads implementation, no resources are associated with +semaphore objects, thus @code{sem_destroy} actually does nothing except +checking that no thread is waiting on the semaphore. This will change +when process-shared semaphores are implemented. +@end deftypefun + +@comment semaphore.h +@comment POSIX +@deftypefun int sem_wait (sem_t * @var{sem}) +@code{sem_wait} suspends the calling thread until the semaphore pointed +to by @var{sem} has non-zero count. It then atomically decreases the +semaphore count. + +@code{sem_wait} is a cancellation point. It always returns 0. +@end deftypefun + +@comment semaphore.h +@comment POSIX +@deftypefun int sem_trywait (sem_t * @var{sem}) +@code{sem_trywait} is a non-blocking variant of @code{sem_wait}. If the +semaphore pointed to by @var{sem} has non-zero count, the count is +atomically decreased and @code{sem_trywait} immediately returns 0. If +the semaphore count is zero, @code{sem_trywait} immediately returns -1 +and sets errno to @code{EAGAIN}. +@end deftypefun + +@comment semaphore.h +@comment POSIX +@deftypefun int sem_post (sem_t * @var{sem}) +@code{sem_post} atomically increases the count of the semaphore pointed to +by @var{sem}. This function never blocks. + +@c !!! This para appears not to agree with the code. +On processors supporting atomic compare-and-swap (Intel 486, Pentium and +later, Alpha, PowerPC, MIPS II, Motorola 68k, Ultrasparc), the +@code{sem_post} function is can safely be called from signal handlers. +This is the only thread synchronization function provided by POSIX +threads that is async-signal safe. On the Intel 386 and earlier Sparc +chips, the current LinuxThreads implementation of @code{sem_post} is not +async-signal safe, because the hardware does not support the required +atomic operations. + +@code{sem_post} always succeeds and returns 0, unless the semaphore +count would exceed @code{SEM_VALUE_MAX} after being incremented. In +that case @code{sem_post} returns -1 and sets @var{errno} to +@code{EINVAL}. The semaphore count is left unchanged. +@end deftypefun + +@comment semaphore.h +@comment POSIX +@deftypefun int sem_getvalue (sem_t * @var{sem}, int * @var{sval}) +@code{sem_getvalue} stores in the location pointed to by @var{sval} the +current count of the semaphore @var{sem}. It always returns 0. +@end deftypefun + +@node Thread-Specific Data +@section Thread-Specific Data + +Programs often need global or static variables that have different +values in different threads. Since threads share one memory space, this +cannot be achieved with regular variables. Thread-specific data is the +POSIX threads answer to this need. + +Each thread possesses a private memory block, the thread-specific data +area, or TSD area for short. This area is indexed by TSD keys. The TSD +area associates values of type @code{void *} to TSD keys. TSD keys are +common to all threads, but the value associated with a given TSD key can +be different in each thread. + +For concreteness, the TSD areas can be viewed as arrays of @code{void *} +pointers, TSD keys as integer indices into these arrays, and the value +of a TSD key as the value of the corresponding array element in the +calling thread. + +When a thread is created, its TSD area initially associates @code{NULL} +with all keys. + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_key_create (pthread_key_t *@var{key}, void (*destr_function) (void *)) +@code{pthread_key_create} allocates a new TSD key. The key is stored in +the location pointed to by @var{key}. There is a limit of +@code{PTHREAD_KEYS_MAX} on the number of keys allocated at a given +time. The value initially associated with the returned key is +@code{NULL} in all currently executing threads. + +The @var{destr_function} argument, if not @code{NULL}, specifies a +destructor function associated with the key. When a thread terminates +via @code{pthread_exit} or by cancellation, @var{destr_function} is +called on the value associated with the key in that thread. The +@var{destr_function} is not called if a key is deleted with +@code{pthread_key_delete} or a value is changed with +@code{pthread_setspecific}. The order in which destructor functions are +called at thread termination time is unspecified. + +Before the destructor function is called, the @code{NULL} value is +associated with the key in the current thread. A destructor function +might, however, re-associate non-@code{NULL} values to that key or some +other key. To deal with this, if after all the destructors have been +called for all non-@code{NULL} values, there are still some +non-@code{NULL} values with associated destructors, then the process is +repeated. The LinuxThreads implementation stops the process after +@code{PTHREAD_DESTRUCTOR_ITERATIONS} iterations, even if some +non-@code{NULL} values with associated descriptors remain. Other +implementations may loop indefinitely. + +@code{pthread_key_create} returns 0 unless @code{PTHREAD_KEYS_MAX} keys +have already been allocated, in which case it fails and returns +@code{EAGAIN}. +@end deftypefun + + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_key_delete (pthread_key_t @var{key}) +@code{pthread_key_delete} deallocates a TSD key. It does not check +whether non-@code{NULL} values are associated with that key in the +currently executing threads, nor call the destructor function associated +with the key. + +If there is no such key @var{key}, it returns @code{EINVAL}. Otherwise +it returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_setspecific (pthread_key_t @var{key}, const void *@var{pointer}) +@code{pthread_setspecific} changes the value associated with @var{key} +in the calling thread, storing the given @var{pointer} instead. + +If there is no such key @var{key}, it returns @code{EINVAL}. Otherwise +it returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun {void *} pthread_getspecific (pthread_key_t @var{key}) +@code{pthread_getspecific} returns the value currently associated with +@var{key} in the calling thread. + +If there is no such key @var{key}, it returns @code{NULL}. +@end deftypefun + +The following code fragment allocates a thread-specific array of 100 +characters, with automatic reclaimation at thread exit: + +@smallexample +/* Key for the thread-specific buffer */ +static pthread_key_t buffer_key; + +/* Once-only initialisation of the key */ +static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT; + +/* Allocate the thread-specific buffer */ +void buffer_alloc(void) +@{ + pthread_once(&buffer_key_once, buffer_key_alloc); + pthread_setspecific(buffer_key, malloc(100)); +@} + +/* Return the thread-specific buffer */ +char * get_buffer(void) +@{ + return (char *) pthread_getspecific(buffer_key); +@} + +/* Allocate the key */ +static void buffer_key_alloc() +@{ + pthread_key_create(&buffer_key, buffer_destroy); +@} + +/* Free the thread-specific buffer */ +static void buffer_destroy(void * buf) +@{ + free(buf); +@} +@end smallexample + +@node Threads and Signal Handling +@section Threads and Signal Handling + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_sigmask (int @var{how}, const sigset_t *@var{newmask}, sigset_t *@var{oldmask}) +@code{pthread_sigmask} changes the signal mask for the calling thread as +described by the @var{how} and @var{newmask} arguments. If @var{oldmask} +is not @code{NULL}, the previous signal mask is stored in the location +pointed to by @var{oldmask}. + +The meaning of the @var{how} and @var{newmask} arguments is the same as +for @code{sigprocmask}. If @var{how} is @code{SIG_SETMASK}, the signal +mask is set to @var{newmask}. If @var{how} is @code{SIG_BLOCK}, the +signals specified to @var{newmask} are added to the current signal mask. +If @var{how} is @code{SIG_UNBLOCK}, the signals specified to +@var{newmask} are removed from the current signal mask. + +Recall that signal masks are set on a per-thread basis, but signal +actions and signal handlers, as set with @code{sigaction}, are shared +between all threads. + +The @code{pthread_sigmask} function returns 0 on success, and one of the +following error codes on error: +@table @code +@item EINVAL +@var{how} is not one of @code{SIG_SETMASK}, @code{SIG_BLOCK}, or @code{SIG_UNBLOCK} + +@item EFAULT +@var{newmask} or @var{oldmask} point to invalid addresses +@end table +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_kill (pthread_t @var{thread}, int @var{signo}) +@code{pthread_kill} sends signal number @var{signo} to the thread +@var{thread}. The signal is delivered and handled as described in +@ref{Signal Handling}. + +@code{pthread_kill} returns 0 on success, one of the following error codes +on error: +@table @code +@item EINVAL +@var{signo} is not a valid signal number + +@item ESRCH +The thread @var{thread} does not exist (e.g. it has already terminated) +@end table +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int sigwait (const sigset_t *@var{set}, int *@var{sig}) +@code{sigwait} suspends the calling thread until one of the signals in +@var{set} is delivered to the calling thread. It then stores the number +of the signal received in the location pointed to by @var{sig} and +returns. The signals in @var{set} must be blocked and not ignored on +entrance to @code{sigwait}. If the delivered signal has a signal handler +function attached, that function is @emph{not} called. + +@code{sigwait} is a cancellation point. It always returns 0. +@end deftypefun + +For @code{sigwait} to work reliably, the signals being waited for must be +blocked in all threads, not only in the calling thread, since +otherwise the POSIX semantics for signal delivery do not guarantee +that it's the thread doing the @code{sigwait} that will receive the signal. +The best way to achieve this is block those signals before any threads +are created, and never unblock them in the program other than by +calling @code{sigwait}. + +Signal handling in LinuxThreads departs significantly from the POSIX +standard. According to the standard, ``asynchronous'' (external) signals +are addressed to the whole process (the collection of all threads), +which then delivers them to one particular thread. The thread that +actually receives the signal is any thread that does not currently block +the signal. + +In LinuxThreads, each thread is actually a kernel process with its own +PID, so external signals are always directed to one particular thread. +If, for instance, another thread is blocked in @code{sigwait} on that +signal, it will not be restarted. + +The LinuxThreads implementation of @code{sigwait} installs dummy signal +handlers for the signals in @var{set} for the duration of the +wait. Since signal handlers are shared between all threads, other +threads must not attach their own signal handlers to these signals, or +alternatively they should all block these signals (which is recommended +anyway). + +@node Miscellaneous Thread Functions +@section Miscellaneous Thread Functions + +@comment pthread.h +@comment POSIX +@deftypefun {pthread_t} pthread_self (@var{void}) +@code{pthread_self} returns the thread identifier for the calling thread. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_equal (pthread_t thread1, pthread_t thread2) +@code{pthread_equal} determines if two thread identifiers refer to the same +thread. + +A non-zero value is returned if @var{thread1} and @var{thread2} refer to +the same thread. Otherwise, 0 is returned. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_detach (pthread_t @var{th}) +@code{pthread_detach} puts the thread @var{th} in the detached +state. This guarantees that the memory resources consumed by @var{th} +will be freed immediately when @var{th} terminates. However, this +prevents other threads from synchronizing on the termination of @var{th} +using @code{pthread_join}. + +A thread can be created initially in the detached state, using the +@code{detachstate} attribute to @code{pthread_create}. In contrast, +@code{pthread_detach} applies to threads created in the joinable state, +and which need to be put in the detached state later. + +After @code{pthread_detach} completes, subsequent attempts to perform +@code{pthread_join} on @var{th} will fail. If another thread is already +joining the thread @var{th} at the time @code{pthread_detach} is called, +@code{pthread_detach} does nothing and leaves @var{th} in the joinable +state. + +On success, 0 is returned. On error, one of the following codes is +returned: +@table @code +@item ESRCH +No thread could be found corresponding to that specified by @var{th} +@item EINVAL +The thread @var{th} is already in the detached state +@end table +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_atfork (void (*@var{prepare})(void), void (*@var{parent})(void), void (*@var{child})(void)) + +@code{pthread_atfork} registers handler functions to be called just +before and just after a new process is created with @code{fork}. The +@var{prepare} handler will be called from the parent process, just +before the new process is created. The @var{parent} handler will be +called from the parent process, just before @code{fork} returns. The +@var{child} handler will be called from the child process, just before +@code{fork} returns. + +@code{pthread_atfork} returns 0 on success and a non-zero error code on +error. + +One or more of the three handlers @var{prepare}, @var{parent} and +@var{child} can be given as @code{NULL}, meaning that no handler needs +to be called at the corresponding point. + +@code{pthread_atfork} can be called several times to install several +sets of handlers. At @code{fork} time, the @var{prepare} handlers are +called in LIFO order (last added with @code{pthread_atfork}, first +called before @code{fork}), while the @var{parent} and @var{child} +handlers are called in FIFO order (first added, first called). + +If there is insufficient memory available to register the handlers, +@code{pthread_atfork} fails and returns @code{ENOMEM}. Otherwise it +returns 0. +@end deftypefun + +To understand the purpose of @code{pthread_atfork}, recall that +@code{fork} duplicates the whole memory space, including mutexes in +their current locking state, but only the calling thread: other threads +are not running in the child process. Thus, if a mutex is locked by a +thread other than the thread calling @code{fork}, that mutex will remain +locked forever in the child process, possibly blocking the execution of +the child process. To avoid this, install handlers with +@code{pthread_atfork} as follows: the @var{prepare} handler locks the +global mutexes (in locking order), and the @var{parent} and @var{child} +handlers unlock them (in reverse order). Alternatively, @var{prepare} +and @var{parent} can be set to @code{NULL} and @var{child} to a function +that calls @code{pthread_mutex_init} on the global mutexes. + +@comment pthread.h +@comment GNU +@deftypefun void pthread_kill_other_threads_np (@var{void}) +@code{pthread_kill_other_threads_np} is a non-portable LinuxThreads extension. +It causes all threads in the program to terminate immediately, except +the calling thread which proceeds normally. It is intended to be +called just before a thread calls one of the @code{exec} functions, +e.g. @code{execve}. + +Termination of the other threads is not performed through +@code{pthread_cancel} and completely bypasses the cancellation +mechanism. Hence, the current settings for cancellation state and +cancellation type are ignored, and the cleanup handlers are not +executed in the terminated threads. + +According to POSIX 1003.1c, a successful @code{exec*} in one of the +threads should automatically terminate all other threads in the program. +This behavior is not yet implemented in LinuxThreads. Calling +@code{pthread_kill_other_threads_np} before @code{exec*} achieves much +of the same behavior, except that if @code{exec*} ultimately fails, then +all other threads are already killed. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_once (pthread_once_t *once_@var{control}, void (*@var{init_routine}) (void)) + +The purpose of @code{pthread_once} is to ensure that a piece of +initialization code is executed at most once. The @var{once_control} +argument points to a static or extern variable statically initialized +to @code{PTHREAD_ONCE_INIT}. + +The first time @code{pthread_once} is called with a given +@var{once_control} argument, it calls @var{init_routine} with no +argument and changes the value of the @var{once_control} variable to +record that initialization has been performed. Subsequent calls to +@code{pthread_once} with the same @code{once_control} argument do +nothing. + +@code{pthread_once} always returns 0. +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_setschedparam (pthread_t target_@var{thread}, int @var{policy}, const struct sched_param *@var{param}) + +@code{pthread_setschedparam} sets the scheduling parameters for the +thread @var{target_thread} as indicated by @var{policy} and +@var{param}. @var{policy} can be either @code{SCHED_OTHER} (regular, +non-realtime scheduling), @code{SCHED_RR} (realtime, round-robin) or +@code{SCHED_FIFO} (realtime, first-in first-out). @var{param} specifies +the scheduling priority for the two realtime policies. See +@code{sched_setpolicy} for more information on scheduling policies. + +The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO} +are available only to processes with superuser privileges. + +On success, @code{pthread_setschedparam} returns 0. On error it returns +one of the following codes: +@table @code +@item EINVAL +@var{policy} is not one of @code{SCHED_OTHER}, @code{SCHED_RR}, +@code{SCHED_FIFO}, or the priority value specified by @var{param} is not +valid for the specified policy + +@item EPERM +Realtime scheduling was requested but the calling process does not have +sufficient privileges. + +@item ESRCH +The @var{target_thread} is invalid or has already terminated + +@item EFAULT +@var{param} points outside the process memory space +@end table +@end deftypefun + +@comment pthread.h +@comment POSIX +@deftypefun int pthread_getschedparam (pthread_t target_@var{thread}, int *@var{policy}, struct sched_param *@var{param}) + +@code{pthread_getschedparam} retrieves the scheduling policy and +scheduling parameters for the thread @var{target_thread} and stores them +in the locations pointed to by @var{policy} and @var{param}, +respectively. + +@code{pthread_getschedparam} returns 0 on success, or one of the +following error codes on failure: +@table @code +@item ESRCH +The @var{target_thread} is invalid or has already terminated. + +@item EFAULT +@var{policy} or @var{param} point outside the process memory space. + +@end table +@end deftypefun diff --git a/manual/.cvsignore b/manual/.cvsignore index 9249469..01f8968 100644 --- a/manual/.cvsignore +++ b/manual/.cvsignore @@ -5,7 +5,7 @@ TODO COPYING* AUTHORS copyr-* copying.* glibc-* *.dvi* *.info* *.c.texi *.ps -*.toc *.aux *.log +*.toc *.aux *.log *.tmp *.cp *.cps *.fn *.fns *.vr *.vrs *.tp *.tps *.ky *.kys *.pg *.pgs chapters chapters-incl1 chapters-incl2 summary.texi stamp-* diff --git a/manual/Makefile b/manual/Makefile index c5ca263..8af1d6c 100644 --- a/manual/Makefile +++ b/manual/Makefile @@ -41,47 +41,37 @@ all: info info: libc.info dir-add.info endif -# Set chapters and chapters-incl[12]. --include chapters -chapters: libc.texinfo - $(find-includes) -ifdef chapters -# @includes in chapter files --include chapters-incl1 -chapters-incl1: $(chapters) - $(find-includes) -chapters-incl1 := $(filter-out summary.texi,$(chapters-incl1)) -endif -ifdef chapters-incl1 -# @includes in files included by chapter files, if any --include chapters-incl2 -chapters-incl2: $(chapters-incl1) - $(find-includes) -endif - -chapters-incl := $(chapters-incl1) $(chapters-incl2) - -define find-includes -(echo '$(@F) :=' \\ ;\ - $(AWK) '$$1 == "@include" { print $$2 " \\" }' $^) > $@.new -mv -f $@.new $@ -endef - # scripts we use ifndef move-if-change move-if-change = ./move-if-change endif mkinstalldirs = $(..)scripts/mkinstalldirs -libc.dvi libc.info: $(chapters) summary.texi $(chapters-incl) +chapters = $(addsuffix .texi, \ + intro errno memory ctype string mbyte locale message search \ + pattern io stdio llio filesys pipe socket terminal math \ + arith time setjmp signal startup process job nss users \ + sysinfo conf) +add-chapters = $(wildcard $(patsubst %, ../%.texi, \ + $(join $(add-ons:=/),$(add-ons)))) +appendices = lang.texi header.texi install.texi maint.texi contrib.texi + +-include texis +texis: $(chapters) $(add-chapters) $(appendices) lgpl.texinfo + $(AWK) -f texis.awk $^ > $@.T + mv -f $@.T $@ + +nonexamples = $(filter-out %.c.texi, $(texis)) +examples = $(filter %.c.texi, $(texis)) + +# Kludge: implicit rule so Make knows the one command does it all. +chapters.% top-menu.%: $(texis) + AWK=$(AWK) $(SHELL) libc-texinfo.sh \ + '$(chapters)' '$(add-chapters)' '$(appendices)' + +libc.dvi libc.info: chapters.texi top-menu.texi libc.dvi: texinfo.tex -%.info: %.texinfo - $(MAKEINFO) $< - -%.dvi: %.texinfo - $(TEXI2DVI) $< - # Generate the summary from the Texinfo source files for each chapter. summary.texi: stamp-summary ; stamp-summary: summary.awk $(chapters) $(chapters-incl) @@ -93,7 +83,7 @@ stamp-summary: summary.awk $(chapters) $(chapters-incl) # Generate a file which can be added to the `dir' content to provide direct # access to the documentation of the function, variables, and other # definitions. -dir-add.texinfo: xtract-typefun.awk $(chapters) $(chapters-incl) +dir-add.texinfo: xtract-typefun.awk $(texis) (echo "@dircategory GNU C library functions"; \ echo "@direntry"; \ $(AWK) -f $^; \ @@ -109,18 +99,22 @@ dir-add.texinfo: xtract-typefun.awk $(chapters) $(chapters-incl) $< | expand > $@.new mv -f $@.new $@ +%.info: %.texinfo + $(MAKEINFO) $< + +%.dvi: %.texinfo + $(TEXI2DVI) $< + +# Distribution. +minimal-dist = summary.awk texis.awk libc-texinfo.sh libc.texinfo \ + $(filter-out summary.texi, $(nonexamples)) \ + $(patsubst %.c.texi,examples/%.c, $(examples)) -minimal-dist = summary.awk libc.texinfo $(chapters) \ - $(patsubst %.c.texi,examples/%.c, \ - $(filter-out summary.texi,$(chapters-incl))) doc-only-dist = Makefile COPYING.LIB -distribute = $(minimal-dist) \ - $(patsubst examples/%.c,%.c.texi,$(filter examples/%.c, \ - $(minimal-dist))) \ - libc.info* libc.?? libc.??s texinfo.tex summary.texi \ - stamp-summary chapters chapters-incl1 chapters-incl2 \ +distribute = $(minimal-dist) $(examples) texis stdio-fp.c \ + libc.info* libc.?? libc.??s texinfo.tex stamp-summary \ xtract-typefun.awk dir-add.texinfo dir-add.info dir \ - stdio-fp.c + chapters.texi top-menu.texi export distribute := $(distribute) tar-it = tar chovf $@ $^ @@ -149,15 +143,17 @@ glibc-doc-$(edition).tar: $(doc-only-dist) $(distribute) .PHONY: mostlyclean distclean realclean clean mostlyclean: - -rm -f libc.dvi libc.info* dir-add.info stubs + -rm -f libc.dvi libc.tmp libc.info* dir-add.info + -rm -f $(objpfx)stubs $(objpfx)distinfo -rm -f $(foreach o,$(object-suffixes-for-libc),$(objpfx)stamp$o) clean: mostlyclean distclean: clean indices = cp fn pg tp vr ky realclean: distclean - -rm -f chapters chapters-incl* summary.texi stamp-summary *.c.texi + -rm -f texis summary.texi stamp-summary *.c.texi -rm -f $(foreach index,$(indices),libc.$(index) libc.$(index)s) - -rm -f libc.log libc.aux libc.toc dir-add.texi + -rm -f libc.log libc.aux libc.toc dir-add.texinfo + -rm -f top-menu.texi chapters.texi .PHONY: install subdir_install installdirs install-data install-data subdir_install: install diff --git a/manual/arith.texi b/manual/arith.texi index 8822a8c..bb7ec34 100644 --- a/manual/arith.texi +++ b/manual/arith.texi @@ -1,30 +1,6 @@ -@c We need some definitions here. -@c No we don't, they were done by math.texi. -zw -@ignore -@ifclear cdot -@ifhtml -@set cdot · -@macro mul -· -@end macro -@end ifhtml -@iftex -@set cdot · -@macro mul -@cdot -@end macro -@end iftex -@ifclear cdot -@set cdot x -@macro mul -x -@end macro -@end ifclear -@end ifclear -@end ignore - @node Arithmetic, Date and Time, Mathematics, Top -@chapter Low-Level Arithmetic Functions +@c %MENU% Low level arithmetic functions +@chapter Arithmetic Functions This chapter contains information about functions for doing basic arithmetic operations, such as splitting a float into its integer and @@ -33,176 +9,145 @@ These functions are declared in the header files @file{math.h} and @file{complex.h}. @menu -* Infinity:: What is Infinity and how to test for it. -* Not a Number:: Making NaNs and testing for NaNs. -* Imaginary Unit:: Constructing complex Numbers. -* Predicates on Floats:: Testing for infinity and for NaNs. -* Floating-Point Classes:: Classify floating-point numbers. -* Operations on Complex:: Projections, Conjugates, and Decomposing. -* Absolute Value:: Absolute value functions. -* Normalization Functions:: Hacks for radix-2 representations. -* Rounding and Remainders:: Determining the integer and - fractional parts of a float. -* Arithmetic on FP Values:: Setting and Modifying Single Bits of FP Values. -* Special arithmetic on FPs:: Special Arithmetic on FPs. -* Integer Division:: Functions for performing integer - division. -* Parsing of Numbers:: Functions for ``reading'' numbers - from strings. -* Old-style number conversion:: Low-level number to string conversion. +* Floating Point Numbers:: Basic concepts. IEEE 754. +* Floating Point Classes:: The five kinds of floating-point number. +* Floating Point Errors:: When something goes wrong in a calculation. +* Rounding:: Controlling how results are rounded. +* Control Functions:: Saving and restoring the FPU's state. +* Arithmetic Functions:: Fundamental operations provided by the library. +* Complex Numbers:: The types. Writing complex constants. +* Operations on Complex:: Projection, conjugation, decomposition. +* Integer Division:: Integer division with guaranteed rounding. +* Parsing of Numbers:: Converting strings to numbers. +* System V Number Conversion:: An archaic way to convert numbers to strings. @end menu -@node Infinity -@section Infinity Values -@cindex Infinity +@node Floating Point Numbers +@section Floating Point Numbers +@cindex floating point +@cindex IEEE 754 @cindex IEEE floating point -Mathematical operations easily can produce as the result values which -are not representable by the floating-point format. The functions in -the mathematics library also have this problem. The situation is -generally solved by raising an overflow exception and by returning a -huge value. +Most computer hardware has support for two different kinds of numbers: +integers (@math{@dots{}-3, -2, -1, 0, 1, 2, 3@dots{}}) and +floating-point numbers. Floating-point numbers have three parts: the +@dfn{mantissa}, the @dfn{exponent}, and the @dfn{sign bit}. The real +number represented by a floating-point value is given by +@tex +$(s \mathrel? -1 \mathrel: 1) \cdot 2^e \cdot M$ +@end tex +@ifnottex +@math{(s ? -1 : 1) @mul{} 2^e @mul{} M} +@end ifnottex +where @math{s} is the sign bit, @math{e} the exponent, and @math{M} +the mantissa. @xref{Floating Point Concepts}, for details. (It is +possible to have a different @dfn{base} for the exponent, but all modern +hardware uses @math{2}.) + +Floating-point numbers can represent a finite subset of the real +numbers. While this subset is large enough for most purposes, it is +important to remember that the only reals that can be represented +exactly are rational numbers that have a terminating binary expansion +shorter than the width of the mantissa. Even simple fractions such as +@math{1/5} can only be approximated by floating point. + +Mathematical operations and functions frequently need to produce values +that are not representable. Often these values can be approximated +closely enough for practical purposes, but sometimes they can't. +Historically there was no way to tell when the results of a calculation +were inaccurate. Modern computers implement the @w{IEEE 754} standard +for numerical computations, which defines a framework for indicating to +the program when the results of calculation are not trustworthy. This +framework consists of a set of @dfn{exceptions} that indicate why a +result could not be represented, and the special values @dfn{infinity} +and @dfn{not a number} (NaN). + +@node Floating Point Classes +@section Floating-Point Number Classification Functions +@cindex floating-point classes +@cindex classes, floating-point +@pindex math.h -The @w{IEEE 754} floating-point defines a special value to be used in -these situations. There is a special value for infinity. +@w{ISO C 9x} defines macros that let you determine what sort of +floating-point number a variable holds. @comment math.h @comment ISO -@deftypevr Macro float INFINITY -An expression representing the infinite value. @code{INFINITY} values are -produced by mathematical operations like @code{1.0 / 0.0}. It is -possible to continue the computations with this value since the basic -operations as well as the mathematical library functions are prepared to -handle values like this. - -Beside @code{INFINITY} also the value @code{-INFINITY} is representable -and it is handled differently if needed. It is possible to test a -value for infiniteness using a simple comparison but the -recommended way is to use the @code{isinf} function. - -This macro was introduced in the @w{ISO C 9X} standard. -@end deftypevr - -@vindex HUGE_VAL -The macros @code{HUGE_VAL}, @code{HUGE_VALF} and @code{HUGE_VALL} are -defined in a similar way but they are not required to represent the -infinite value, only a very large value (@pxref{Domain and Range Errors}). -If actually infinity is wanted, @code{INFINITY} should be used. - - -@node Not a Number -@section ``Not a Number'' Values -@cindex NaN -@cindex not a number -@cindex IEEE floating point +@deftypefn {Macro} int fpclassify (@emph{float-type} @var{x}) +This is a generic macro which works on all floating-point types and +which returns a value of type @code{int}. The possible values are: -The IEEE floating point format used by most modern computers supports -values that are ``not a number''. These values are called @dfn{NaNs}. -``Not a number'' values result from certain operations which have no -meaningful numeric result, such as zero divided by zero or infinity -divided by infinity. +@vtable @code +@item FP_NAN +The floating-point number @var{x} is ``Not a Number'' (@pxref{Infinity +and NaN}) +@item FP_INFINITE +The value of @var{x} is either plus or minus infinity (@pxref{Infinity +and NaN}) +@item FP_ZERO +The value of @var{x} is zero. In floating-point formats like @w{IEEE +754}, where zero can be signed, this value is also returned if +@var{x} is negative zero. +@item FP_SUBNORMAL +Numbers whose absolute value is too small to be represented in the +normal format are represented in an alternate, @dfn{denormalized} format +(@pxref{Floating Point Concepts}). This format is less precise but can +represent values closer to zero. @code{fpclassify} returns this value +for values of @var{x} in this alternate format. +@item FP_NORMAL +This value is returned for all other values of @var{x}. It indicates +that there is nothing special about the number. +@end vtable -One noteworthy property of NaNs is that they are not equal to -themselves. Thus, @code{x == x} can be 0 if the value of @code{x} is a -NaN. You can use this to test whether a value is a NaN or not: if it is -not equal to itself, then it is a NaN. But the recommended way to test -for a NaN is with the @code{isnan} function (@pxref{Predicates on Floats}). +@end deftypefn -Almost any arithmetic operation in which one argument is a NaN returns -a NaN. +@code{fpclassify} is most useful if more than one property of a number +must be tested. There are more specific macros which only test one +property at a time. Generally these macros execute faster than +@code{fpclassify}, since there is special hardware support for them. +You should therefore use the specific macros whenever possible. @comment math.h -@comment GNU -@deftypevr Macro float NAN -An expression representing a value which is ``not a number''. This -macro is a GNU extension, available only on machines that support ``not -a number'' values---that is to say, on all machines that support IEEE -floating point. - -You can use @samp{#ifdef NAN} to test whether the machine supports -NaNs. (Of course, you must arrange for GNU extensions to be visible, -such as by defining @code{_GNU_SOURCE}, and then you must include -@file{math.h}.) -@end deftypevr - -@node Imaginary Unit -@section Constructing complex Numbers - -@pindex complex.h -To construct complex numbers it is necessary have a way to express the -imaginary part of the numbers. In mathematics one uses the symbol ``i'' -to mark a number as imaginary. For convenience the @file{complex.h} -header defines two macros which allow to use a similar easy notation. - -@deftypevr Macro {const float complex} _Complex_I -This macro is a representation of the complex number ``@math{0+1i}''. -Computing - -@smallexample -_Complex_I * _Complex_I = -1 -@end smallexample - -@noindent -leads to a real-valued result. If no @code{imaginary} types are -available it is easiest to use this value to construct complex numbers -from real values: +@comment ISO +@deftypefn {Macro} int isfinite (@emph{float-type} @var{x}) +This macro returns a nonzero value if @var{x} is finite: not plus or +minus infinity, and not NaN. It is equivalent to @smallexample -3.0 - _Complex_I * 4.0 +(fpclassify (x) != FP_NAN && fpclassify (x) != FP_INFINITE) @end smallexample -@end deftypevr -@noindent -Without an optimizing compiler this is more expensive than the use of -@code{_Imaginary_I} but with is better than nothing. You can avoid all -the hassles if you use the @code{I} macro below if the name is not -problem. +@code{isfinite} is implemented as a macro which accepts any +floating-point type. +@end deftypefn -@deftypevr Macro {const float imaginary} _Imaginary_I -This macro is a representation of the value ``@math{1i}''. I.e., it is -the value for which +@comment math.h +@comment ISO +@deftypefn {Macro} int isnormal (@emph{float-type} @var{x}) +This macro returns a nonzero value if @var{x} is finite and normalized. +It is equivalent to @smallexample -_Imaginary_I * _Imaginary_I = -1 +(fpclassify (x) == FP_NORMAL) @end smallexample +@end deftypefn -@noindent -The result is not of type @code{float imaginary} but instead @code{float}. -One can use it to easily construct complex number like in +@comment math.h +@comment ISO +@deftypefn {Macro} int isnan (@emph{float-type} @var{x}) +This macro returns a nonzero value if @var{x} is NaN. It is equivalent +to @smallexample -3.0 - _Imaginary_I * 4.0 +(fpclassify (x) == FP_NAN) @end smallexample +@end deftypefn -@noindent -which results in the complex number with a real part of 3.0 and a -imaginary part -4.0. -@end deftypevr - -@noindent -A more intuitive approach is to use the following macro. - -@deftypevr Macro {const float imaginary} I -This macro has exactly the same value as @code{_Imaginary_I}. The -problem is that the name @code{I} very easily can clash with macros or -variables in programs and so it might be a good idea to avoid this name -and stay at the safe side by using @code{_Imaginary_I}. - -If the implementation does not support the @code{imaginary} types -@code{I} is defined as @code{_Complex_I} which is the second best -solution. It still can be used in the same way but requires a most -clever compiler to get the same results. -@end deftypevr - - -@node Predicates on Floats -@section Predicates on Floats - -@pindex math.h -This section describes some miscellaneous test functions on doubles. -Prototypes for these functions appear in @file{math.h}. These are BSD -functions, and thus are available if you define @code{_BSD_SOURCE} or -@code{_GNU_SOURCE}. +Another set of floating-point classification functions was provided by +BSD. The GNU C library also supports these functions; however, we +recommend that you use the C9x macros in new code. Those are standard +and will be available more widely. Also, since they are macros, you do +not have to worry about the type of their argument. @comment math.h @comment BSD @@ -219,15 +164,16 @@ This function returns @code{-1} if @var{x} represents negative infinity, @deftypefunx int isnanf (float @var{x}) @deftypefunx int isnanl (long double @var{x}) This function returns a nonzero value if @var{x} is a ``not a number'' -value, and zero otherwise. (You can just as well use @code{@var{x} != -@var{x}} to get the same result). +value, and zero otherwise. -However, @code{isnan} will not raise an invalid exception if @var{x} is -a signalling NaN, while @code{@var{x} != @var{x}} will. This makes -@code{isnan} much slower than the alternative; in code where performance -matters and signalling NaNs are unimportant, it's usually better to use -@code{@var{x} != @var{x}}, even though this is harder to understand. +@strong{Note:} The @code{isnan} macro defined by @w{ISO C 9x} overrides +the BSD function. This is normally not a problem, because the two +routines behave identically. However, if you really need to get the BSD +function for some reason, you can write +@smallexample +(isnan) (x) +@end smallexample @end deftypefun @comment math.h @@ -242,12 +188,11 @@ number'' value, and zero otherwise. @comment math.h @comment BSD @deftypefun double infnan (int @var{error}) -This function is provided for compatibility with BSD. The other -mathematical functions use @code{infnan} to decide what to return on -occasion of an error. Its argument is an error code, @code{EDOM} or -@code{ERANGE}; @code{infnan} returns a suitable value to indicate this -with. @code{-ERANGE} is also acceptable as an argument, and corresponds -to @code{-HUGE_VAL} as a value. +This function is provided for compatibility with BSD. Its argument is +an error code, @code{EDOM} or @code{ERANGE}; @code{infnan} returns the +value that a math function would return if it set @code{errno} to that +value. @xref{Math Error Reporting}. @code{-ERANGE} is also acceptable +as an argument, and corresponds to @code{-HUGE_VAL} as a value. In the BSD library, on certain machines, @code{infnan} raises a fatal signal in all cases. The GNU library does not do likewise, because that @@ -257,182 +202,602 @@ does not fit the @w{ISO C} specification. @strong{Portability Note:} The functions listed in this section are BSD extensions. -@node Floating-Point Classes -@section Floating-Point Number Classification Functions -Instead of using the BSD specific functions from the last section it is -better to use those in this section which are introduced in the @w{ISO C -9X} standard and are therefore widely available. +@node Floating Point Errors +@section Errors in Floating-Point Calculations + +@menu +* FP Exceptions:: IEEE 754 math exceptions and how to detect them. +* Infinity and NaN:: Special values returned by calculations. +* Status bit operations:: Checking for exceptions after the fact. +* Math Error Reporting:: How the math functions report errors. +@end menu + +@node FP Exceptions +@subsection FP Exceptions +@cindex exception +@cindex signal +@cindex zero divide +@cindex division by zero +@cindex inexact exception +@cindex invalid exception +@cindex overflow exception +@cindex underflow exception + +The @w{IEEE 754} standard defines five @dfn{exceptions} that can occur +during a calculation. Each corresponds to a particular sort of error, +such as overflow. + +When exceptions occur (when exceptions are @dfn{raised}, in the language +of the standard), one of two things can happen. By default the +exception is simply noted in the floating-point @dfn{status word}, and +the program continues as if nothing had happened. The operation +produces a default value, which depends on the exception (see the table +below). Your program can check the status word to find out which +exceptions happened. + +Alternatively, you can enable @dfn{traps} for exceptions. In that case, +when an exception is raised, your program will receive the @code{SIGFPE} +signal. The default action for this signal is to terminate the +program. @xref{Signal Handling} for how you can change the effect of +the signal. + +@findex matherr +In the System V math library, the user-defined function @code{matherr} +is called when certain exceptions occur inside math library functions. +However, the Unix98 standard deprecates this interface. We support it +for historical compatibility, but recommend that you do not use it in +new programs. + +@noindent +The exceptions defined in @w{IEEE 754} are: + +@table @samp +@item Invalid Operation +This exception is raised if the given operands are invalid for the +operation to be performed. Examples are +(see @w{IEEE 754}, @w{section 7}): +@enumerate +@item +Addition or subtraction: @math{@infinity{} - @infinity{}}. (But +@math{@infinity{} + @infinity{} = @infinity{}}). +@item +Multiplication: @math{0 @mul{} @infinity{}}. +@item +Division: @math{0/0} or @math{@infinity{}/@infinity{}}. +@item +Remainder: @math{x} REM @math{y}, where @math{y} is zero or @math{x} is +infinite. +@item +Square root if the operand is less then zero. More generally, any +mathematical function evaluated outside its domain produces this +exception. +@item +Conversion of a floating-point number to an integer or decimal +string, when the number cannot be represented in the target format (due +to overflow, infinity, or NaN). +@item +Conversion of an unrecognizable input string. +@item +Comparison via predicates involving @math{<} or @math{>}, when one or +other of the operands is NaN. You can prevent this exception by using +the unordered comparison functions instead; see @ref{FP Comparison Functions}. +@end enumerate + +If the exception does not trap, the result of the operation is NaN. + +@item Division by Zero +This exception is raised when a finite nonzero number is divided +by zero. If no trap occurs the result is either @math{+@infinity{}} or +@math{-@infinity{}}, depending on the signs of the operands. + +@item Overflow +This exception is raised whenever the result cannot be represented +as a finite value in the precision format of the destination. If no trap +occurs the result depends on the sign of the intermediate result and the +current rounding mode (@w{IEEE 754}, @w{section 7.3}): +@enumerate +@item +Round to nearest carries all overflows to @math{@infinity{}} +with the sign of the intermediate result. +@item +Round toward @math{0} carries all overflows to the largest representable +finite number with the sign of the intermediate result. +@item +Round toward @math{-@infinity{}} carries positive overflows to the +largest representable finite number and negative overflows to +@math{-@infinity{}}. + +@item +Round toward @math{@infinity{}} carries negative overflows to the +most negative representable finite number and positive overflows +to @math{@infinity{}}. +@end enumerate + +Whenever the overflow exception is raised, the inexact exception is also +raised. + +@item Underflow +The underflow exception is raised when an intermediate result is too +small to be calculated accurately, or if the operation's result rounded +to the destination precision is too small to be normalized. + +When no trap is installed for the underflow exception, underflow is +signaled (via the underflow flag) only when both tininess and loss of +accuracy have been detected. If no trap handler is installed the +operation continues with an imprecise small value, or zero if the +destination precision cannot hold the small exact result. + +@item Inexact +This exception is signalled if a rounded result is not exact (such as +when calculating the square root of two) or a result overflows without +an overflow trap. +@end table + +@node Infinity and NaN +@subsection Infinity and NaN +@cindex infinity +@cindex not a number +@cindex NaN + +@w{IEEE 754} floating point numbers can represent positive or negative +infinity, and @dfn{NaN} (not a number). These three values arise from +calculations whose result is undefined or cannot be represented +accurately. You can also deliberately set a floating-point variable to +any of them, which is sometimes useful. Some examples of calculations +that produce infinity or NaN: + +@ifnottex +@smallexample +@math{1/0 = @infinity{}} +@math{log (0) = -@infinity{}} +@math{sqrt (-1) = NaN} +@end smallexample +@end ifnottex +@tex +$${1\over0} = \infty$$ +$$\log 0 = -\infty$$ +$$\sqrt{-1} = \hbox{NaN}$$ +@end tex + +When a calculation produces any of these values, an exception also +occurs; see @ref{FP Exceptions}. + +The basic operations and math functions all accept infinity and NaN and +produce sensible output. Infinities propagate through calculations as +one would expect: for example, @math{2 + @infinity{} = @infinity{}}, +@math{4/@infinity{} = 0}, atan @math{(@infinity{}) = @pi{}/2}. NaN, on +the other hand, infects any calculation that involves it. Unless the +calculation would produce the same result no matter what real value +replaced NaN, the result is NaN. + +In comparison operations, positive infinity is larger than all values +except itself and NaN, and negative infinity is smaller than all values +except itself and NaN. NaN is @dfn{unordered}: it is not equal to, +greater than, or less than anything, @emph{including itself}. @code{x == +x} is false if the value of @code{x} is NaN. You can use this to test +whether a value is NaN or not, but the recommended way to test for NaN +is with the @code{isnan} function (@pxref{Floating Point Classes}). In +addition, @code{<}, @code{>}, @code{<=}, and @code{>=} will raise an +exception when applied to NaNs. + +@file{math.h} defines macros that allow you to explicitly set a variable +to infinity or NaN. @comment math.h @comment ISO -@deftypefn {Macro} int fpclassify (@emph{float-type} @var{x}) -This is a generic macro which works on all floating-point types and -which returns a value of type @code{int}. The possible values are: +@deftypevr Macro float INFINITY +An expression representing positive infinity. It is equal to the value +produced by mathematical operations like @code{1.0 / 0.0}. +@code{-INFINITY} represents negative infinity. + +You can test whether a floating-point value is infinite by comparing it +to this macro. However, this is not recommended; you should use the +@code{isfinite} macro instead. @xref{Floating Point Classes}. + +This macro was introduced in the @w{ISO C 9X} standard. +@end deftypevr + +@comment math.h +@comment GNU +@deftypevr Macro float NAN +An expression representing a value which is ``not a number''. This +macro is a GNU extension, available only on machines that support the +``not a number'' value---that is to say, on all machines that support +IEEE floating point. + +You can use @samp{#ifdef NAN} to test whether the machine supports +NaN. (Of course, you must arrange for GNU extensions to be visible, +such as by defining @code{_GNU_SOURCE}, and then you must include +@file{math.h}.) +@end deftypevr + +@w{IEEE 754} also allows for another unusual value: negative zero. This +value is produced when you divide a positive number by negative +infinity, or when a negative result is smaller than the limits of +representation. Negative zero behaves identically to zero in all +calculations, unless you explicitly test the sign bit with +@code{signbit} or @code{copysign}. + +@node Status bit operations +@subsection Examining the FPU status word + +@w{ISO C 9x} defines functions to query and manipulate the +floating-point status word. You can use these functions to check for +untrapped exceptions when it's convenient, rather than worrying about +them in the middle of a calculation. + +These constants represent the various @w{IEEE 754} exceptions. Not all +FPUs report all the different exceptions. Each constant is defined if +and only if the FPU you are compiling for supports that exception, so +you can test for FPU support with @samp{#ifdef}. They are defined in +@file{fenv.h}. @vtable @code -@item FP_NAN -The floating-point number @var{x} is ``Not a Number'' (@pxref{Not a Number}) -@item FP_INFINITE -The value of @var{x} is either plus or minus infinity (@pxref{Infinity}) -@item FP_ZERO -The value of @var{x} is zero. In floating-point formats like @w{IEEE -754} where the zero value can be signed this value is also returned if -@var{x} is minus zero. -@item FP_SUBNORMAL -Some floating-point formats (such as @w{IEEE 754}) allow floating-point -numbers to be represented in a denormalized format. This happens if the -absolute value of the number is too small to be represented in the -normal format. @code{FP_SUBNORMAL} is returned for such values of @var{x}. -@item FP_NORMAL -This value is returned for all other cases which means the number is a -plain floating-point number without special meaning. +@comment fenv.h +@comment ISO +@item FE_INEXACT + The inexact exception. +@comment fenv.h +@comment ISO +@item FE_DIVBYZERO + The divide by zero exception. +@comment fenv.h +@comment ISO +@item FE_UNDERFLOW + The underflow exception. +@comment fenv.h +@comment ISO +@item FE_OVERFLOW + The overflow exception. +@comment fenv.h +@comment ISO +@item FE_INVALID + The invalid exception. @end vtable -This macro is useful if more than property of a number must be -tested. If one only has to test for, e.g., a NaN value, there are -function which are faster. -@end deftypefn +The macro @code{FE_ALL_EXCEPT} is the bitwise OR of all exception macros +which are supported by the FP implementation. -The remainder of this section introduces some more specific functions. -They might be implemented faster than the call to @code{fpclassify} and -if the actual need in the program is covered be these functions they -should be used (and not @code{fpclassify}). +These functions allow you to clear exception flags, test for exceptions, +and save and restore the set of exceptions flagged. -@comment math.h +@comment fenv.h @comment ISO -@deftypefn {Macro} int isfinite (@emph{float-type} @var{x}) -The value returned by this macro is nonzero if the value of @var{x} is -not plus or minus infinity and not NaN. I.e., it could be implemented as +@deftypefun void feclearexcept (int @var{excepts}) +This function clears all of the supported exception flags indicated by +@var{excepts}. +@end deftypefun + +@comment fenv.h +@comment ISO +@deftypefun int fetestexcept (int @var{excepts}) +Test whether the exception flags indicated by the parameter @var{except} +are currently set. If any of them are, a nonzero value is returned +which specifies which exceptions are set. Otherwise the result is zero. +@end deftypefun + +To understand these functions, imagine that the status word is an +integer variable named @var{status}. @code{feclearexcept} is then +equivalent to @samp{status &= ~excepts} and @code{fetestexcept} is +equivalent to @samp{(status & excepts)}. The actual implementation may +be very different, of course. + +Exception flags are only cleared when the program explicitly requests it, +by calling @code{feclearexcept}. If you want to check for exceptions +from a set of calculations, you should clear all the flags first. Here +is a simple example of the way to use @code{fetestexcept}: @smallexample -(fpclassify (x) != FP_NAN && fpclassify (x) != FP_INFINITE) +@{ + double f; + int raised; + feclearexcept (FE_ALL_EXCEPT); + f = compute (); + raised = fetestexcept (FE_OVERFLOW | FE_INVALID); + if (raised & FE_OVERFLOW) @{ /* ... */ @} + if (raised & FE_INVALID) @{ /* ... */ @} + /* ... */ +@} @end smallexample -@code{isfinite} is also implemented as a macro which can handle all -floating-point types. Programs should use this function instead of -@var{finite} (@pxref{Predicates on Floats}). -@end deftypefn +You cannot explicitly set bits in the status word. You can, however, +save the entire status word and restore it later. This is done with the +following functions: -@comment math.h +@comment fenv.h @comment ISO -@deftypefn {Macro} int isnormal (@emph{float-type} @var{x}) -If @code{isnormal} returns a nonzero value the value or @var{x} is -neither a NaN, infinity, zero, nor a denormalized number. I.e., it -could be implemented as +@deftypefun void fegetexceptflag (fexcept_t *@var{flagp}, int @var{excepts}) +This function stores in the variable pointed to by @var{flagp} an +implementation-defined value representing the current setting of the +exception flags indicated by @var{excepts}. +@end deftypefun -@smallexample -(fpclassify (x) == FP_NORMAL) -@end smallexample -@end deftypefn +@comment fenv.h +@comment ISO +@deftypefun void fesetexceptflag (const fexcept_t *@var{flagp}, int +@var{excepts}) +This function restores the flags for the exceptions indicated by +@var{excepts} to the values stored in the variable pointed to by +@var{flagp}. +@end deftypefun + +Note that the value stored in @code{fexcept_t} bears no resemblance to +the bit mask returned by @code{fetestexcept}. The type may not even be +an integer. Do not attempt to modify an @code{fexcept_t} variable. + +@node Math Error Reporting +@subsection Error Reporting by Mathematical Functions +@cindex errors, mathematical +@cindex domain error +@cindex range error + +Many of the math functions are defined only over a subset of the real or +complex numbers. Even if they are mathematically defined, their result +may be larger or smaller than the range representable by their return +type. These are known as @dfn{domain errors}, @dfn{overflows}, and +@dfn{underflows}, respectively. Math functions do several things when +one of these errors occurs. In this manual we will refer to the +complete response as @dfn{signalling} a domain error, overflow, or +underflow. + +When a math function suffers a domain error, it raises the invalid +exception and returns NaN. It also sets @var{errno} to @code{EDOM}; +this is for compatibility with old systems that do not support @w{IEEE +754} exception handling. Likewise, when overflow occurs, math +functions raise the overflow exception and return @math{@infinity{}} or +@math{-@infinity{}} as appropriate. They also set @var{errno} to +@code{ERANGE}. When underflow occurs, the underflow exception is +raised, and zero (appropriately signed) is returned. @var{errno} may be +set to @code{ERANGE}, but this is not guaranteed. + +Some of the math functions are defined mathematically to result in a +complex value over parts of their domains. The most familiar example of +this is taking the square root of a negative number. The complex math +functions, such as @code{csqrt}, will return the appropriate complex value +in this case. The real-valued functions, such as @code{sqrt}, will +signal a domain error. + +Some older hardware does not support infinities. On that hardware, +overflows instead return a particular very large number (usually the +largest representable number). @file{math.h} defines macros you can use +to test for overflow on both old and new hardware. @comment math.h @comment ISO -@deftypefn {Macro} int isnan (@emph{float-type} @var{x}) -The situation with this macro is a bit complicated. Here @code{isnan} -is a macro which can handle all kinds of floating-point types. It -returns a nonzero value is @var{x} does not represent a NaN value and -could be written like this +@deftypevr Macro double HUGE_VAL +@deftypevrx Macro float HUGE_VALF +@deftypevrx Macro {long double} HUGE_VALL +An expression representing a particular very large number. On machines +that use @w{IEEE 754} floating point format, @code{HUGE_VAL} is infinity. +On other machines, it's typically the largest positive number that can +be represented. + +Mathematical functions return the appropriately typed version of +@code{HUGE_VAL} or @code{@minus{}HUGE_VAL} when the result is too large +to be represented. +@end deftypevr -@smallexample -(fpclassify (x) == FP_NAN) -@end smallexample +@node Rounding +@section Rounding Modes + +Floating-point calculations are carried out internally with extra +precision, and then rounded to fit into the destination type. This +ensures that results are as precise as the input data. @w{IEEE 754} +defines four possible rounding modes: + +@table @asis +@item Round to nearest. +This is the default mode. It should be used unless there is a specific +need for one of the others. In this mode results are rounded to the +nearest representable value. If the result is midway between two +representable values, the even representable is chosen. @dfn{Even} here +means the lowest-order bit is zero. This rounding mode prevents +statistical bias and guarantees numeric stability: round-off errors in a +lengthy calculation will remain smaller than half of @code{FLT_EPSILON}. + +@c @item Round toward @math{+@infinity{}} +@item Round toward plus Infinity. +All results are rounded to the smallest representable value +which is greater than the result. + +@c @item Round toward @math{-@infinity{}} +@item Round toward minus Infinity. +All results are rounded to the largest representable value which is less +than the result. + +@item Round toward zero. +All results are rounded to the largest representable value whose +magnitude is less than that of the result. In other words, if the +result is negative it is rounded up; if it is positive, it is rounded +down. +@end table -The complication is that there is a function of the same name and the -same semantic defined for compatibility with BSD (@pxref{Predicates on -Floats}). Fortunately this should not yield to problems in most cases -since the macro and the function have the same semantic. Should in a -situation the function be absolutely necessary one can use +@noindent +@file{fenv.h} defines constants which you can use to refer to the +various rounding modes. Each one will be defined if and only if the FPU +supports the corresponding rounding mode. -@smallexample -(isnan) (x) -@end smallexample +@table @code +@comment fenv.h +@comment ISO +@vindex FE_TONEAREST +@item FE_TONEAREST +Round to nearest. -@noindent -to avoid the macro expansion. Using the macro has two big advantages: -it is more portable and one does not have to choose the right function -among @code{isnan}, @code{isnanf}, and @code{isnanl}. -@end deftypefn +@comment fenv.h +@comment ISO +@vindex FE_UPWARD +@item FE_UPWARD +Round toward @math{+@infinity{}}. +@comment fenv.h +@comment ISO +@vindex FE_DOWNWARD +@item FE_DOWNWARD +Round toward @math{-@infinity{}}. -@node Operations on Complex -@section Projections, Conjugates, and Decomposing of Complex Numbers -@cindex project complex numbers -@cindex conjugate complex numbers -@cindex decompose complex numbers +@comment fenv.h +@comment ISO +@vindex FE_TOWARDZERO +@item FE_TOWARDZERO +Round toward zero. +@end table -This section lists functions performing some of the simple mathematical -operations on complex numbers. Using any of the function requires that -the C compiler understands the @code{complex} keyword, introduced to the -C language in the @w{ISO C 9X} standard. +Underflow is an unusual case. Normally, @w{IEEE 754} floating point +numbers are always normalized (@pxref{Floating Point Concepts}). +Numbers smaller than @math{2^r} (where @math{r} is the minimum exponent, +@code{FLT_MIN_RADIX-1} for @var{float}) cannot be represented as +normalized numbers. Rounding all such numbers to zero or @math{2^r} +would cause some algorithms to fail at 0. Therefore, they are left in +denormalized form. That produces loss of precision, since some bits of +the mantissa are stolen to indicate the decimal point. + +If a result is too small to be represented as a denormalized number, it +is rounded to zero. However, the sign of the result is preserved; if +the calculation was negative, the result is @dfn{negative zero}. +Negative zero can also result from some operations on infinity, such as +@math{4/-@infinity{}}. Negative zero behaves identically to zero except +when the @code{copysign} or @code{signbit} functions are used to check +the sign bit directly. + +At any time one of the above four rounding modes is selected. You can +find out which one with this function: + +@comment fenv.h +@comment ISO +@deftypefun int fegetround (void) +Returns the currently selected rounding mode, represented by one of the +values of the defined rounding mode macros. +@end deftypefun -@pindex complex.h -The prototypes for all functions in this section can be found in -@file{complex.h}. All functions are available in three variants, one -for each of the three floating-point types. +@noindent +To change the rounding mode, use this function: -The easiest operation on complex numbers is the decomposition in the -real part and the imaginary part. This is done by the next two -functions. +@comment fenv.h +@comment ISO +@deftypefun int fesetround (int @var{round}) +Changes the currently selected rounding mode to @var{round}. If +@var{round} does not correspond to one of the supported rounding modes +nothing is changed. @code{fesetround} returns a nonzero value if it +changed the rounding mode, zero if the mode is not supported. +@end deftypefun -@comment complex.h +You should avoid changing the rounding mode if possible. It can be an +expensive operation; also, some hardware requires you to compile your +program differently for it to work. The resulting code may run slower. +See your compiler documentation for details. +@c This section used to claim that functions existed to round one number +@c in a specific fashion. I can't find any functions in the library +@c that do that. -zw + +@node Control Functions +@section Floating-Point Control Functions + +@w{IEEE 754} floating-point implementations allow the programmer to +decide whether traps will occur for each of the exceptions, by setting +bits in the @dfn{control word}. In C, traps result in the program +receiving the @code{SIGFPE} signal; see @ref{Signal Handling}. + +@strong{Note:} @w{IEEE 754} says that trap handlers are given details of +the exceptional situation, and can set the result value. C signals do +not provide any mechanism to pass this information back and forth. +Trapping exceptions in C is therefore not very useful. + +It is sometimes necessary to save the state of the floating-point unit +while you perform some calculation. The library provides functions +which save and restore the exception flags, the set of exceptions that +generate traps, and the rounding mode. This information is known as the +@dfn{floating-point environment}. + +The functions to save and restore the floating-point environment all use +a variable of type @code{fenv_t} to store information. This type is +defined in @file{fenv.h}. Its size and contents are +implementation-defined. You should not attempt to manipulate a variable +of this type directly. + +To save the state of the FPU, use one of these functions: + +@comment fenv.h @comment ISO -@deftypefun double creal (complex double @var{z}) -@deftypefunx float crealf (complex float @var{z}) -@deftypefunx {long double} creall (complex long double @var{z}) -These functions return the real part of the complex number @var{z}. +@deftypefun void fegetenv (fenv_t *@var{envp}) +Store the floating-point environment in the variable pointed to by +@var{envp}. @end deftypefun -@comment complex.h +@comment fenv.h @comment ISO -@deftypefun double cimag (complex double @var{z}) -@deftypefunx float cimagf (complex float @var{z}) -@deftypefunx {long double} cimagl (complex long double @var{z}) -These functions return the imaginary part of the complex number @var{z}. +@deftypefun int feholdexcept (fenv_t *@var{envp}) +Store the current floating-point environment in the object pointed to by +@var{envp}. Then clear all exception flags, and set the FPU to trap no +exceptions. Not all FPUs support trapping no exceptions; if +@code{feholdexcept} cannot set this mode, it returns zero. If it +succeeds, it returns a nonzero value. @end deftypefun +The functions which restore the floating-point environment can take two +kinds of arguments: -The conjugate complex value of a given complex number has the same value -for the real part but the complex part is negated. +@itemize @bullet +@item +Pointers to @code{fenv_t} objects, which were initialized previously by a +call to @code{fegetenv} or @code{feholdexcept}. +@item +@vindex FE_DFL_ENV +The special macro @code{FE_DFL_ENV} which represents the floating-point +environment as it was available at program start. +@item +Implementation defined macros with names starting with @code{FE_}. -@comment complex.h +@vindex FE_NOMASK_ENV +If possible, the GNU C Library defines a macro @code{FE_NOMASK_ENV} +which represents an environment where every exception raised causes a +trap to occur. You can test for this macro using @code{#ifdef}. It is +only defined if @code{_GNU_SOURCE} is defined. + +Some platforms might define other predefined environments. +@end itemize + +@noindent +To set the floating-point environment, you can use either of these +functions: + +@comment fenv.h @comment ISO -@deftypefun {complex double} conj (complex double @var{z}) -@deftypefunx {complex float} conjf (complex float @var{z}) -@deftypefunx {complex long double} conjl (complex long double @var{z}) -These functions return the conjugate complex value of the complex number -@var{z}. +@deftypefun void fesetenv (const fenv_t *@var{envp}) +Set the floating-point environment to that described by @var{envp}. @end deftypefun -@comment complex.h +@comment fenv.h @comment ISO -@deftypefun double carg (complex double @var{z}) -@deftypefunx float cargf (complex float @var{z}) -@deftypefunx {long double} cargl (complex long double @var{z}) -These functions return argument of the complex number @var{z}. - -Mathematically, the argument is the phase angle of @var{z} with a branch -cut along the negative real axis. +@deftypefun void feupdateenv (const fenv_t *@var{envp}) +Like @code{fesetenv}, this function sets the floating-point environment +to that described by @var{envp}. However, if any exceptions were +flagged in the status word before @code{feupdateenv} was called, they +remain flagged after the call. In other words, after @code{feupdateenv} +is called, the status word is the bitwise OR of the previous status word +and the one saved in @var{envp}. @end deftypefun -@comment complex.h -@comment ISO -@deftypefun {complex double} cproj (complex double @var{z}) -@deftypefunx {complex float} cprojf (complex float @var{z}) -@deftypefunx {complex long double} cprojl (complex long double @var{z}) -Return the projection of the complex value @var{z} on the Riemann -sphere. Values with a infinite complex part (even if the real part -is NaN) are projected to positive infinite on the real axis. If the -real part is infinite, the result is equivalent to +@node Arithmetic Functions +@section Arithmetic Functions -@smallexample -INFINITY + I * copysign (0.0, cimag (z)) -@end smallexample -@end deftypefun +The C library provides functions to do basic operations on +floating-point numbers. These include absolute value, maximum and minimum, +normalization, bit twiddling, rounding, and a few others. +@menu +* Absolute Value:: Absolute values of integers and floats. +* Normalization Functions:: Extracting exponents and putting them back. +* Rounding Functions:: Rounding floats to integers. +* Remainder Functions:: Remainders on division, precisely defined. +* FP Bit Twiddling:: Sign bit adjustment. Adding epsilon. +* FP Comparison Functions:: Comparisons without risk of exceptions. +* Misc FP Arithmetic:: Max, min, positive difference, multiply-add. +@end menu @node Absolute Value -@section Absolute Value +@subsection Absolute Value @cindex absolute value functions These functions are provided for obtaining the @dfn{absolute value} (or @@ -445,33 +810,21 @@ whose imaginary part is @var{y}, the absolute value is @w{@code{sqrt @pindex math.h @pindex stdlib.h Prototypes for @code{abs}, @code{labs} and @code{llabs} are in @file{stdlib.h}; -@code{fabs}, @code{fabsf} and @code{fabsl} are declared in @file{math.h}; +@code{fabs}, @code{fabsf} and @code{fabsl} are declared in @file{math.h}. @code{cabs}, @code{cabsf} and @code{cabsl} are declared in @file{complex.h}. @comment stdlib.h @comment ISO @deftypefun int abs (int @var{number}) -This function returns the absolute value of @var{number}. +@deftypefunx {long int} labs (long int @var{number}) +@deftypefunx {long long int} llabs (long long int @var{number}) +These functions return the absolute value of @var{number}. Most computers use a two's complement integer representation, in which the absolute value of @code{INT_MIN} (the smallest possible @code{int}) cannot be represented; thus, @w{@code{abs (INT_MIN)}} is not defined. -@end deftypefun -@comment stdlib.h -@comment ISO -@deftypefun {long int} labs (long int @var{number}) -This is similar to @code{abs}, except that both the argument and result -are of type @code{long int} rather than @code{int}. -@end deftypefun - -@comment stdlib.h -@comment ISO -@deftypefun {long long int} llabs (long long int @var{number}) -This is similar to @code{abs}, except that both the argument and result -are of type @code{long long int} rather than @code{int}. - -This function is defined in @w{ISO C 9X}. +@code{llabs} is new to @w{ISO C 9x} @end deftypefun @comment math.h @@ -488,24 +841,21 @@ This function returns the absolute value of the floating-point number @deftypefun double cabs (complex double @var{z}) @deftypefunx float cabsf (complex float @var{z}) @deftypefunx {long double} cabsl (complex long double @var{z}) -These functions return the absolute value of the complex number @var{z}. -The compiler must support complex numbers to use these functions. The -value is: +These functions return the absolute value of the complex number @var{z} +(@pxref{Complex Numbers}). The absolute value of a complex number is: @smallexample sqrt (creal (@var{z}) * creal (@var{z}) + cimag (@var{z}) * cimag (@var{z})) @end smallexample -This function should always be used instead of the direct formula since -using the simple straight-forward method can mean to lose accuracy. If -one of the squared values is neglectable in size compared to the other -value the result should be the same as the larger value. But squaring -the value and afterwards using the square root function leads to -inaccuracy. See @code{hypot} in @xref{Exponents and Logarithms}. +This function should always be used instead of the direct formula +because it takes special care to avoid losing precision. It may also +take advantage of hardware support for this operation. See @code{hypot} +in @xref{Exponents and Logarithms}. @end deftypefun @node Normalization Functions -@section Normalization Functions +@subsection Normalization Functions @cindex normalization functions (floating-point) The functions described in this section are primarily provided as a way @@ -553,23 +903,15 @@ by @code{frexp}.) For example, @code{ldexp (0.8, 4)} returns @code{12.8}. @end deftypefun -The following functions which come from BSD provide facilities -equivalent to those of @code{ldexp} and @code{frexp}: - -@comment math.h -@comment BSD -@deftypefun double scalb (double @var{value}, int @var{exponent}) -@deftypefunx float scalbf (float @var{value}, int @var{exponent}) -@deftypefunx {long double} scalbl (long double @var{value}, int @var{exponent}) -The @code{scalb} function is the BSD name for @code{ldexp}. -@end deftypefun +The following functions, which come from BSD, provide facilities +equivalent to those of @code{ldexp} and @code{frexp}. @comment math.h @comment BSD @deftypefun double logb (double @var{x}) @deftypefunx float logbf (float @var{x}) @deftypefunx {long double} logbl (long double @var{x}) -These BSD functions return the integer part of the base-2 logarithm of +These functions return the integer part of the base-2 logarithm of @var{x}, an integer value represented in type @code{double}. This is the highest integer power of @code{2} contained in @var{x}. The sign of @var{x} is ignored. For example, @code{logb (3.5)} is @code{1.0} and @@ -578,25 +920,62 @@ the highest integer power of @code{2} contained in @var{x}. The sign of When @code{2} raised to this power is divided into @var{x}, it gives a quotient between @code{1} (inclusive) and @code{2} (exclusive). -If @var{x} is zero, the value is minus infinity (if the machine supports -such a value), or else a very small number. If @var{x} is infinity, the -value is infinity. +If @var{x} is zero, the return value is minus infinity if the machine +supports infinities, and a very small number if it does not. If @var{x} +is infinity, the return value is infinity. + +For finite @var{x}, the value returned by @code{logb} is one less than +the value that @code{frexp} would store into @code{*@var{exponent}}. +@end deftypefun + +@comment math.h +@comment BSD +@deftypefun double scalb (double @var{value}, int @var{exponent}) +@deftypefunx float scalbf (float @var{value}, int @var{exponent}) +@deftypefunx {long double} scalbl (long double @var{value}, int @var{exponent}) +The @code{scalb} function is the BSD name for @code{ldexp}. +@end deftypefun + +@comment math.h +@comment BSD +@deftypefun {long long int} scalbn (double @var{x}, int n) +@deftypefunx {long long int} scalbnf (float @var{x}, int n) +@deftypefunx {long long int} scalbnl (long double @var{x}, int n) +@code{scalbn} is identical to @code{scalb}, except that the exponent +@var{n} is an @code{int} instead of a floating-point number. +@end deftypefun + +@comment math.h +@comment BSD +@deftypefun {long long int} scalbln (double @var{x}, long int n) +@deftypefunx {long long int} scalblnf (float @var{x}, long int n) +@deftypefunx {long long int} scalblnl (long double @var{x}, long int n) +@code{scalbln} is identical to @code{scalb}, except that the exponent +@var{n} is a @code{long int} instead of a floating-point number. +@end deftypefun -The value returned by @code{logb} is one less than the value that -@code{frexp} would store into @code{*@var{exponent}}. +@comment math.h +@comment BSD +@deftypefun {long long int} significand (double @var{x}) +@deftypefunx {long long int} significandf (float @var{x}) +@deftypefunx {long long int} significandl (long double @var{x}) +@code{significand} returns the mantissa of @var{x} scaled to the range +@math{[1, 2)}. +It is equivalent to @w{@code{scalb (@var{x}, (double) -ilogb (@var{x}))}}. + +This function exists mainly for use in certain standardized tests +of @w{IEEE 754} conformance. @end deftypefun -@node Rounding and Remainders -@section Rounding and Remainder Functions -@cindex rounding functions -@cindex remainder functions +@node Rounding Functions +@subsection Rounding Functions @cindex converting floats to integers @pindex math.h -The functions listed here perform operations such as rounding, -truncation, and remainder in division of floating point numbers. Some -of these functions convert floating point numbers to integer values. -They are all declared in @file{math.h}. +The functions listed here perform operations such as rounding and +truncation of floating-point values. Some of these functions convert +floating point numbers to integer values. They are all declared in +@file{math.h}. You can also convert floating-point numbers to integers simply by casting them to @code{int}. This discards the fractional part, @@ -627,6 +1006,14 @@ integer, returning that value as a @code{double}. Thus, @code{floor @comment math.h @comment ISO +@deftypefun double trunc (double @var{x}) +@deftypefunx float truncf (float @var{x}) +@deftypefunx {long double} truncl (long double @var{x}) +@code{trunc} is another name for @code{floor} +@end deftypefun + +@comment math.h +@comment ISO @deftypefun double rint (double @var{x}) @deftypefunx float rintf (float @var{x}) @deftypefunx {long double} rintl (long double @var{x}) @@ -635,7 +1022,10 @@ current rounding mode. @xref{Floating Point Parameters}, for information about the various rounding modes. The default rounding mode is to round to the nearest integer; some machines support other modes, but round-to-nearest is always used unless -you explicit select another. +you explicitly select another. + +If @var{x} was not initially an integer, these functions raise the +inexact exception. @end deftypefun @comment math.h @@ -643,26 +1033,78 @@ you explicit select another. @deftypefun double nearbyint (double @var{x}) @deftypefunx float nearbyintf (float @var{x}) @deftypefunx {long double} nearbyintl (long double @var{x}) -These functions return the same value as the @code{rint} functions but -even some rounding actually takes place @code{nearbyint} does @emph{not} -raise the inexact exception. +These functions return the same value as the @code{rint} functions, but +do not raise the inexact exception if @var{x} is not an integer. +@end deftypefun + +@comment math.h +@comment ISO +@deftypefun double round (double @var{x}) +@deftypefunx float roundf (float @var{x}) +@deftypefunx {long double} roundl (long double @var{x}) +These functions are similar to @code{rint}, but they round halfway +cases away from zero instead of to the nearest even integer. +@end deftypefun + +@comment math.h +@comment ISO +@deftypefun {long int} lrint (double @var{x}) +@deftypefunx {long int} lrintf (float @var{x}) +@deftypefunx {long int} lrintl (long double @var{x}) +These functions are just like @code{rint}, but they return a +@code{long int} instead of a floating-point number. +@end deftypefun + +@comment math.h +@comment ISO +@deftypefun {long long int} llrint (double @var{x}) +@deftypefunx {long long int} llrintf (float @var{x}) +@deftypefunx {long long int} llrintl (long double @var{x}) +These functions are just like @code{rint}, but they return a +@code{long long int} instead of a floating-point number. @end deftypefun @comment math.h @comment ISO +@deftypefun {long int} lround (double @var{x}) +@deftypefunx {long int} lroundf (float @var{x}) +@deftypefunx {long int} lroundl (long double @var{x}) +These functions are just like @code{round}, but they return a +@code{long int} instead of a floating-point number. +@end deftypefun + +@comment math.h +@comment ISO +@deftypefun {long long int} llround (double @var{x}) +@deftypefunx {long long int} llroundf (float @var{x}) +@deftypefunx {long long int} llroundl (long double @var{x}) +These functions are just like @code{round}, but they return a +@code{long long int} instead of a floating-point number. +@end deftypefun + + +@comment math.h +@comment ISO @deftypefun double modf (double @var{value}, double *@var{integer-part}) @deftypefunx float modff (float @var{value}, float *@var{integer-part}) @deftypefunx {long double} modfl (long double @var{value}, long double *@var{integer-part}) These functions break the argument @var{value} into an integer part and a fractional part (between @code{-1} and @code{1}, exclusive). Their sum equals @var{value}. Each of the parts has the same sign as @var{value}, -so the rounding of the integer part is towards zero. +and the integer part is always rounded toward zero. @code{modf} stores the integer part in @code{*@var{integer-part}}, and returns the fractional part. For example, @code{modf (2.5, &intpart)} returns @code{0.5} and stores @code{2.0} into @code{intpart}. @end deftypefun +@node Remainder Functions +@subsection Remainder Functions + +The functions in this section compute the remainder on division of two +floating-point numbers. Each is a little different; pick the one that +suits your problem. + @comment math.h @comment ISO @deftypefun double fmod (double @var{numerator}, double @var{denominator}) @@ -678,8 +1120,7 @@ towards zero to an integer. Thus, @w{@code{fmod (6.5, 2.3)}} returns The result has the same sign as the @var{numerator} and has magnitude less than the magnitude of the @var{denominator}. -If @var{denominator} is zero, @code{fmod} fails and sets @code{errno} to -@code{EDOM}. +If @var{denominator} is zero, @code{fmod} signals a domain error. @end deftypefun @comment math.h @@ -687,7 +1128,7 @@ If @var{denominator} is zero, @code{fmod} fails and sets @code{errno} to @deftypefun double drem (double @var{numerator}, double @var{denominator}) @deftypefunx float dremf (float @var{numerator}, float @var{denominator}) @deftypefunx {long double} dreml (long double @var{numerator}, long double @var{denominator}) -These functions are like @code{fmod} etc except that it rounds the +These functions are like @code{fmod} except that they rounds the internal quotient @var{n} to the nearest integer instead of towards zero to an integer. For example, @code{drem (6.5, 2.3)} returns @code{-0.4}, which is @code{6.5} minus @code{6.9}. @@ -698,33 +1139,38 @@ absolute value of the @var{denominator}. The difference between (@var{numerator}, @var{denominator})} is always either @var{denominator}, minus @var{denominator}, or zero. -If @var{denominator} is zero, @code{drem} fails and sets @code{errno} to -@code{EDOM}. +If @var{denominator} is zero, @code{drem} signals a domain error. @end deftypefun +@comment math.h +@comment BSD +@deftypefun double remainder (double @var{numerator}, double @var{denominator}) +@deftypefunx float remainderf (float @var{numerator}, float @var{denominator}) +@deftypefunx {long double} remainderl (long double @var{numerator}, long double @var{denominator}) +This function is another name for @code{drem}. +@end deftypefun -@node Arithmetic on FP Values -@section Setting and modifying Single Bits of FP Values +@node FP Bit Twiddling +@subsection Setting and modifying single bits of FP values @cindex FP arithmetic -In certain situations it is too complicated (or expensive) to modify a -floating-point value by the normal operations. For a few operations -@w{ISO C 9X} defines functions to modify the floating-point value -directly. +There are some operations that are too complicated or expensive to +perform by hand on floating-point numbers. @w{ISO C 9x} defines +functions to do these operations, which mostly involve changing single +bits. @comment math.h @comment ISO @deftypefun double copysign (double @var{x}, double @var{y}) @deftypefunx float copysignf (float @var{x}, float @var{y}) @deftypefunx {long double} copysignl (long double @var{x}, long double @var{y}) -The @code{copysign} function allows to specifiy the sign of the -floating-point value given in the parameter @var{x} by discarding the -prior content and replacing it with the sign of the value @var{y}. -The so found value is returned. +These functions return @var{x} but with the sign of @var{y}. They work +even if @var{x} or @var{y} are NaN or zero. Both of these can carry a +sign (although not all implementations support it) and this is one of +the few operations that can tell the difference. -This function also works and throws no exception if the parameter -@var{x} is a @code{NaN}. If the platform supports the signed zero -representation @var{x} might also be zero. +@code{copysign} never raises an exception. +@c except signalling NaNs This function is defined in @w{IEC 559} (and the appendix with recommended functions in @w{IEEE 754}/@w{IEEE 854}). @@ -737,10 +1183,9 @@ recommended functions in @w{IEEE 754}/@w{IEEE 854}). types. It returns a nonzero value if the value of @var{x} has its sign bit set. -This is not the same as @code{x < 0.0} since in some floating-point -formats (e.g., @w{IEEE 754}) the zero value is optionally signed. The -comparison @code{-0.0 < 0.0} will not be true while @code{signbit -(-0.0)} will return a nonzero value. +This is not the same as @code{x < 0.0}, because @w{IEEE 754} floating +point allows zero to be signed. The comparison @code{-0.0 < 0.0} is +false, but @code{signbit (-0.0)} will return a nonzero value. @end deftypefun @comment math.h @@ -749,58 +1194,151 @@ comparison @code{-0.0 < 0.0} will not be true while @code{signbit @deftypefunx float nextafterf (float @var{x}, float @var{y}) @deftypefunx {long double} nextafterl (long double @var{x}, long double @var{y}) The @code{nextafter} function returns the next representable neighbor of -@var{x} in the direction towards @var{y}. Depending on the used data -type the steps make have a different size. If @math{@var{x} = @var{y}} -the function simply returns @var{x}. If either value is a @code{NaN} -one the @code{NaN} values is returned. Otherwise a value corresponding -to the value of the least significant bit in the mantissa is -added/subtracted (depending on the direction). If the resulting value -is not finite but @var{x} is, overflow is signaled. Underflow is -signaled if the resulting value is a denormalized number (if the @w{IEEE -754}/@w{IEEE 854} representation is used). +@var{x} in the direction towards @var{y}. The size of the step between +@var{x} and the result depends on the type of the result. If +@math{@var{x} = @var{y}} the function simply returns @var{x}. If either +value is @code{NaN}, @code{NaN} is returned. Otherwise +a value corresponding to the value of the least significant bit in the +mantissa is added or subtracted, depending on the direction. +@code{nextafter} will signal overflow or underflow if the result goes +outside of the range of normalized numbers. This function is defined in @w{IEC 559} (and the appendix with recommended functions in @w{IEEE 754}/@w{IEEE 854}). @end deftypefun +@comment math.h +@comment ISO +@deftypefun {long long int} nextafterx (double @var{x}, long double @var{y}) +@deftypefunx {long long int} nextafterxf (float @var{x}, long double @var{y}) +@deftypefunx {long long int} nextafterxl (long double @var{x}, long double @var{y}) +These functions are identical to the corresponding versions of +@code{nextafter} except that their second argument is a @code{long +double}. +@end deftypefun + @cindex NaN @comment math.h @comment ISO @deftypefun double nan (const char *@var{tagp}) @deftypefunx float nanf (const char *@var{tagp}) @deftypefunx {long double} nanl (const char *@var{tagp}) -The @code{nan} function returns a representation of the NaN value. If -quiet NaNs are supported by the platform a call like @code{nan -("@var{n-char-sequence}")} is equivalent to @code{strtod -("NAN(@var{n-char-sequence})")}. The exact implementation is left -unspecified but on systems using IEEE arithmethic the -@var{n-char-sequence} specifies the bits of the mantissa for the NaN -value. +The @code{nan} function returns a representation of NaN, provided that +NaN is supported by the target platform. +@code{nan ("@var{n-char-sequence}")} is equivalent to +@code{strtod ("NAN(@var{n-char-sequence})")}. + +The argument @var{tagp} is used in an unspecified manner. On @w{IEEE +754} systems, there are many representations of NaN, and @var{tagp} +selects one. On other systems it may do nothing. @end deftypefun +@node FP Comparison Functions +@subsection Floating-Point Comparison Functions +@cindex unordered comparison -@node Special arithmetic on FPs -@section Special Arithmetic on FPs -@cindex positive difference +The standard C comparison operators provoke exceptions when one or other +of the operands is NaN. For example, + +@smallexample +int v = a < 1.0; +@end smallexample + +@noindent +will raise an exception if @var{a} is NaN. (This does @emph{not} +happen with @code{==} and @code{!=}; those merely return false and true, +respectively, when NaN is examined.) Frequently this exception is +undesirable. @w{ISO C 9x} therefore defines comparison functions that +do not raise exceptions when NaN is examined. All of the functions are +implemented as macros which allow their arguments to be of any +floating-point type. The macros are guaranteed to evaluate their +arguments only once. + +@comment math.h +@comment ISO +@deftypefn Macro int isgreater (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) +This macro determines whether the argument @var{x} is greater than +@var{y}. It is equivalent to @code{(@var{x}) > (@var{y})}, but no +exception is raised if @var{x} or @var{y} are NaN. +@end deftypefn + +@comment math.h +@comment ISO +@deftypefn Macro int isgreaterequal (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) +This macro determines whether the argument @var{x} is greater than or +equal to @var{y}. It is equivalent to @code{(@var{x}) >= (@var{y})}, but no +exception is raised if @var{x} or @var{y} are NaN. +@end deftypefn + +@comment math.h +@comment ISO +@deftypefn Macro int isless (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) +This macro determines whether the argument @var{x} is less than @var{y}. +It is equivalent to @code{(@var{x}) < (@var{y})}, but no exception is +raised if @var{x} or @var{y} are NaN. +@end deftypefn + +@comment math.h +@comment ISO +@deftypefn Macro int islessequal (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) +This macro determines whether the argument @var{x} is less than or equal +to @var{y}. It is equivalent to @code{(@var{x}) <= (@var{y})}, but no +exception is raised if @var{x} or @var{y} are NaN. +@end deftypefn + +@comment math.h +@comment ISO +@deftypefn Macro int islessgreater (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) +This macro determines whether the argument @var{x} is less or greater +than @var{y}. It is equivalent to @code{(@var{x}) < (@var{y}) || +(@var{x}) > (@var{y})} (although it only evaluates @var{x} and @var{y} +once), but no exception is raised if @var{x} or @var{y} are NaN. + +This macro is not equivalent to @code{@var{x} != @var{y}}, because that +expression is true if @var{x} or @var{y} are NaN. +@end deftypefn + +@comment math.h +@comment ISO +@deftypefn Macro int isunordered (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) +This macro determines whether its arguments are unordered. In other +words, it is true if @var{x} or @var{y} are NaN, and false otherwise. +@end deftypefn + +Not all machines provide hardware support for these operations. On +machines that don't, the macros can be very slow. Therefore, you should +not use these functions when NaN is not a concern. + +@strong{Note:} There are no macros @code{isequal} or @code{isunequal}. +They are unnecessary, because the @code{==} and @code{!=} operators do +@emph{not} throw an exception if one or both of the operands are NaN. + +@node Misc FP Arithmetic +@subsection Miscellaneous FP arithmetic functions @cindex minimum @cindex maximum +@cindex positive difference +@cindex multiply-add -A frequent operation of numbers is the determination of mimuma, maxima, -or the difference between numbers. The @w{ISO C 9X} standard introduces -three functions which implement this efficiently while also providing -some useful functions which is not so efficient to implement. Machine -specific implementation might perform this very efficient. +The functions in this section perform miscellaneous but common +operations that are awkward to express with C operators. On some +processors these functions can use special machine instructions to +perform these operations faster than the equivalent C code. @comment math.h @comment ISO @deftypefun double fmin (double @var{x}, double @var{y}) @deftypefunx float fminf (float @var{x}, float @var{y}) @deftypefunx {long double} fminl (long double @var{x}, long double @var{y}) -The @code{fmin} function determine the minimum of the two values @var{x} -and @var{y} and returns it. +The @code{fmin} function returns the lesser of the two values @var{x} +and @var{y}. It is similar to the expression +@smallexample +((x) < (y) ? (x) : (y)) +@end smallexample +except that @var{x} and @var{y} are only evaluated once. -If an argument is NaN it as treated as missing and the other value is -returned. If both values are NaN one of the values is returned. +If an argument is NaN, the other argument is returned. If both arguments +are NaN, NaN is returned. @end deftypefun @comment math.h @@ -808,11 +1346,11 @@ returned. If both values are NaN one of the values is returned. @deftypefun double fmax (double @var{x}, double @var{y}) @deftypefunx float fmaxf (float @var{x}, float @var{y}) @deftypefunx {long double} fmaxl (long double @var{x}, long double @var{y}) -The @code{fmax} function determine the maximum of the two values @var{x} -and @var{y} and returns it. +The @code{fmax} function returns the greater of the two values @var{x} +and @var{y}. -If an argument is NaN it as treated as missing and the other value is -returned. If both values are NaN one of the values is returned. +If an argument is NaN, the other argument is returned. If both arguments +are NaN, NaN is returned. @end deftypefun @comment math.h @@ -820,13 +1358,11 @@ returned. If both values are NaN one of the values is returned. @deftypefun double fdim (double @var{x}, double @var{y}) @deftypefunx float fdimf (float @var{x}, float @var{y}) @deftypefunx {long double} fdiml (long double @var{x}, long double @var{y}) -The @code{fdim} function computes the positive difference between -@var{x} and @var{y} and returns this value. @dfn{Positive difference} -means that if @var{x} is greater than @var{y} the value @math{@var{x} - -@var{y}} is returned. Otherwise the return value is @math{+0}. +The @code{fdim} function returns the positive difference between +@var{x} and @var{y}. The positive difference is @math{@var{x} - +@var{y}} if @var{x} is greater than @var{y}, and @math{0} otherwise. -If any of the arguments is NaN this value is returned. If both values -are NaN, one of the values is returned. +If @var{x}, @var{y}, or both are NaN, NaN is returned. @end deftypefun @comment math.h @@ -835,39 +1371,192 @@ are NaN, one of the values is returned. @deftypefunx float fmaf (float @var{x}, float @var{y}, float @var{z}) @deftypefunx {long double} fmal (long double @var{x}, long double @var{y}, long double @var{z}) @cindex butterfly -The name of the function @code{fma} means floating-point multiply-add. -I.e., the operation performed is @math{(@var{x} @mul{} @var{y}) + @var{z}}. -The speciality of this function is that the intermediate -result is not rounded and the addition is performed with the full -precision of the multiplcation. - -This function was introduced because some processors provide such a -function in their FPU implementation. Since compilers cannot optimize -code which performs the operation in single steps using this opcode -because of rounding differences the operation is available separately so -the programmer can select when the rounding of the intermediate result -is not important. +The @code{fma} function performs floating-point multiply-add. This is +the operation @math{(@var{x} @mul{} @var{y}) + @var{z}}, but the +intermediate result is not rounded to the destination type. This can +sometimes improve the precision of a calculation. + +This function was introduced because some processors have a special +instruction to perform multiply-add. The C compiler cannot use it +directly, because the expression @samp{x*y + z} is defined to round the +intermediate result. @code{fma} lets you choose when you want to round +only once. @vindex FP_FAST_FMA -If the @file{math.h} header defines the symbol @code{FP_FAST_FMA} (or -@code{FP_FAST_FMAF} and @code{FP_FAST_FMAL} for @code{float} and -@code{long double} respectively) the processor typically defines the -operation in hardware. The symbols might also be defined if the -software implementation is as fast as a multiply and an add but in the -GNU C Library the macros indicate hardware support. +On processors which do not implement multiply-add in hardware, +@code{fma} can be very slow since it must avoid intermediate rounding. +@file{math.h} defines the symbols @code{FP_FAST_FMA}, +@code{FP_FAST_FMAF}, and @code{FP_FAST_FMAL} when the corresponding +version of @code{fma} is no slower than the expression @samp{x*y + z}. +In the GNU C library, this always means the operation is implemented in +hardware. @end deftypefun +@node Complex Numbers +@section Complex Numbers +@pindex complex.h +@cindex complex numbers + +@w{ISO C 9x} introduces support for complex numbers in C. This is done +with a new type qualifier, @code{complex}. It is a keyword if and only +if @file{complex.h} has been included. There are three complex types, +corresponding to the three real types: @code{float complex}, +@code{double complex}, and @code{long double complex}. + +To construct complex numbers you need a way to indicate the imaginary +part of a number. There is no standard notation for an imaginary +floating point constant. Instead, @file{complex.h} defines two macros +that can be used to create complex numbers. + +@deftypevr Macro {const float complex} _Complex_I +This macro is a representation of the complex number ``@math{0+1i}''. +Multiplying a real floating-point value by @code{_Complex_I} gives a +complex number whose value is purely imaginary. You can use this to +construct complex constants: + +@smallexample +@math{3.0 + 4.0i} = @code{3.0 + 4.0 * _Complex_I} +@end smallexample + +Note that @code{_Complex_I * _Complex_I} has the value @code{-1}, but +the type of that value is @code{complex}. +@end deftypevr + +@c Put this back in when gcc supports _Imaginary_I. It's too confusing. +@ignore +@noindent +Without an optimizing compiler this is more expensive than the use of +@code{_Imaginary_I} but with is better than nothing. You can avoid all +the hassles if you use the @code{I} macro below if the name is not +problem. + +@deftypevr Macro {const float imaginary} _Imaginary_I +This macro is a representation of the value ``@math{1i}''. I.e., it is +the value for which + +@smallexample +_Imaginary_I * _Imaginary_I = -1 +@end smallexample + +@noindent +The result is not of type @code{float imaginary} but instead @code{float}. +One can use it to easily construct complex number like in + +@smallexample +3.0 - _Imaginary_I * 4.0 +@end smallexample + +@noindent +which results in the complex number with a real part of 3.0 and a +imaginary part -4.0. +@end deftypevr +@end ignore + +@noindent +@code{_Complex_I} is a bit of a mouthful. @file{complex.h} also defines +a shorter name for the same constant. + +@deftypevr Macro {const float complex} I +This macro has exactly the same value as @code{_Complex_I}. Most of the +time it is preferable. However, it causes problems if you want to use +the identifier @code{I} for something else. You can safely write + +@smallexample +#include +#undef I +@end smallexample + +@noindent +if you need @code{I} for your own purposes. (In that case we recommend +you also define some other short name for @code{_Complex_I}, such as +@code{J}.) + +@ignore +If the implementation does not support the @code{imaginary} types +@code{I} is defined as @code{_Complex_I} which is the second best +solution. It still can be used in the same way but requires a most +clever compiler to get the same results. +@end ignore +@end deftypevr + +@node Operations on Complex +@section Projections, Conjugates, and Decomposing of Complex Numbers +@cindex project complex numbers +@cindex conjugate complex numbers +@cindex decompose complex numbers +@pindex complex.h + +@w{ISO C 9x} also defines functions that perform basic operations on +complex numbers, such as decomposition and conjugation. The prototypes +for all these functions are in @file{complex.h}. All functions are +available in three variants, one for each of the three complex types. + +@comment complex.h +@comment ISO +@deftypefun double creal (complex double @var{z}) +@deftypefunx float crealf (complex float @var{z}) +@deftypefunx {long double} creall (complex long double @var{z}) +These functions return the real part of the complex number @var{z}. +@end deftypefun + +@comment complex.h +@comment ISO +@deftypefun double cimag (complex double @var{z}) +@deftypefunx float cimagf (complex float @var{z}) +@deftypefunx {long double} cimagl (complex long double @var{z}) +These functions return the imaginary part of the complex number @var{z}. +@end deftypefun + +@comment complex.h +@comment ISO +@deftypefun {complex double} conj (complex double @var{z}) +@deftypefunx {complex float} conjf (complex float @var{z}) +@deftypefunx {complex long double} conjl (complex long double @var{z}) +These functions return the conjugate value of the complex number +@var{z}. The conjugate of a complex number has the same real part and a +negated imaginary part. In other words, @samp{conj(a + bi) = a + -bi}. +@end deftypefun + +@comment complex.h +@comment ISO +@deftypefun double carg (complex double @var{z}) +@deftypefunx float cargf (complex float @var{z}) +@deftypefunx {long double} cargl (complex long double @var{z}) +These functions return the argument of the complex number @var{z}. +The argument of a complex number is the angle in the complex plane +between the positive real axis and a line passing through zero and the +number. This angle is measured in the usual fashion and ranges from @math{0} +to @math{2@pi{}}. + +@code{carg} has a branch cut along the positive real axis. +@end deftypefun + +@comment complex.h +@comment ISO +@deftypefun {complex double} cproj (complex double @var{z}) +@deftypefunx {complex float} cprojf (complex float @var{z}) +@deftypefunx {complex long double} cprojl (complex long double @var{z}) +These functions return the projection of the complex value @var{z} onto +the Riemann sphere. Values with a infinite imaginary part are projected +to positive infinity on the real axis, even if the real part is NaN. If +the real part is infinite, the result is equivalent to + +@smallexample +INFINITY + I * copysign (0.0, cimag (z)) +@end smallexample +@end deftypefun @node Integer Division @section Integer Division @cindex integer division functions This section describes functions for performing integer division. These -functions are redundant in the GNU C library, since in GNU C the @samp{/} -operator always rounds towards zero. But in other C implementations, -@samp{/} may round differently with negative arguments. @code{div} and -@code{ldiv} are useful because they specify how to round the quotient: -towards zero. The remainder has the same sign as the numerator. +functions are redundant when GNU CC is used, because in GNU C the +@samp{/} operator always rounds towards zero. But in other C +implementations, @samp{/} may round differently with negative arguments. +@code{div} and @code{ldiv} are useful because they specify how to round +the quotient: towards zero. The remainder has the same sign as the +numerator. These functions are specified to return a result @var{r} such that the value @code{@var{r}.quot*@var{denominator} + @var{r}.rem} equals @@ -940,7 +1629,7 @@ structure of type @code{ldiv_t}. @end deftypefun @comment stdlib.h -@comment GNU +@comment ISO @deftp {Data Type} lldiv_t This is a structure type used to hold the result returned by the @code{lldiv} function. It has the following members: @@ -958,14 +1647,13 @@ type @code{long long int} rather than @code{int}.) @end deftp @comment stdlib.h -@comment GNU +@comment ISO @deftypefun lldiv_t lldiv (long long int @var{numerator}, long long int @var{denominator}) The @code{lldiv} function is like the @code{div} function, but the arguments are of type @code{long long int} and the result is returned as a structure of type @code{lldiv_t}. -The @code{lldiv} function is a GNU extension but it will eventually be -part of the next ISO C standard. +The @code{lldiv} function was added in @w{ISO C 9x}. @end deftypefun @@ -1047,10 +1735,13 @@ representable because of overflow, @code{strtol} returns either appropriate for the sign of the value. It also sets @code{errno} to @code{ERANGE} to indicate there was overflow. -Because the value @code{0l} is a correct result for @code{strtol} the -user who is interested in handling errors should set the global variable -@code{errno} to @code{0} before calling this function, so that the program -can later test whether an error occurred. +You should not check for errors by examining the return value of +@code{strtol}, because the string might be a valid representation of +@code{0l}, @code{LONG_MAX}, or @code{LONG_MIN}. Instead, check whether +@var{tailptr} points to what you expect after the number +(e.g. @code{'\0'} if the string should end after the number). You also +need to clear @var{errno} before the call and check it afterward, in +case there was overflow. There is an example at the end of this section. @end deftypefun @@ -1059,22 +1750,22 @@ There is an example at the end of this section. @comment ISO @deftypefun {unsigned long int} strtoul (const char *@var{string}, char **@var{tailptr}, int @var{base}) The @code{strtoul} (``string-to-unsigned-long'') function is like -@code{strtol} except it deals with unsigned numbers, and returns its -value with type @code{unsigned long int}. If the number has a leading -@samp{-} sign the negated value is returned. The syntax is the same as -described above for @code{strtol}. The value returned in case of -overflow is @code{ULONG_MAX} (@pxref{Range of Type}). - -Like @code{strtol} this function sets @code{errno} and returns the value -@code{0ul} in case the value for @var{base} is not in the legal range. +@code{strtol} except it returns an @code{unsigned long int} value. If +the number has a leading @samp{-} sign, the return value is negated. +The syntax is the same as described above for @code{strtol}. The value +returned on overflow is @code{ULONG_MAX} (@pxref{Range of +Type}). + +@code{strtoul} sets @var{errno} to @code{EINVAL} if @var{base} is out of +range, or @code{ERANGE} on overflow. @end deftypefun @comment stdlib.h -@comment GNU +@comment ISO @deftypefun {long long int} strtoll (const char *@var{string}, char **@var{tailptr}, int @var{base}) -The @code{strtoll} function is like @code{strtol} except that is deals -with extra long numbers and it returns its value with type @code{long -long int}. +The @code{strtoll} function is like @code{strtol} except that it returns +a @code{long long int} value, and accepts numbers with a correspondingly +larger range. If the string has valid syntax for an integer but the value is not representable because of overflow, @code{strtoll} returns either @@ -1082,36 +1773,29 @@ representable because of overflow, @code{strtoll} returns either appropriate for the sign of the value. It also sets @code{errno} to @code{ERANGE} to indicate there was overflow. -The @code{strtoll} function is a GNU extension but it will eventually be -part of the next ISO C standard. +The @code{strtoll} function was introduced in @w{ISO C 9x}. @end deftypefun @comment stdlib.h @comment BSD @deftypefun {long long int} strtoq (const char *@var{string}, char **@var{tailptr}, int @var{base}) -@code{strtoq} (``string-to-quad-word'') is only an commonly used other -name for the @code{strtoll} function. Everything said for -@code{strtoll} applies to @code{strtoq} as well. +@code{strtoq} (``string-to-quad-word'') is the BSD name for @code{strtoll}. @end deftypefun @comment stdlib.h -@comment GNU +@comment ISO @deftypefun {unsigned long long int} strtoull (const char *@var{string}, char **@var{tailptr}, int @var{base}) -The @code{strtoull} function is like @code{strtoul} except that is deals -with extra long numbers and it returns its value with type -@code{unsigned long long int}. The value returned in case of overflow +The @code{strtoull} function is like @code{strtoul} except that it +returns an @code{unsigned long long int}. The value returned on overflow is @code{ULONG_LONG_MAX} (@pxref{Range of Type}). -The @code{strtoull} function is a GNU extension but it will eventually be -part of the next ISO C standard. +The @code{strtoull} function was introduced in @w{ISO C 9x}. @end deftypefun @comment stdlib.h @comment BSD @deftypefun {unsigned long long int} strtouq (const char *@var{string}, char **@var{tailptr}, int @var{base}) -@code{strtouq} (``string-to-unsigned-quad-word'') is only an commonly -used other name for the @code{strtoull} function. Everything said for -@code{strtoull} applies to @code{strtouq} as well. +@code{strtouq} is the BSD name for @code{strtoull}. @end deftypefun @comment stdlib.h @@ -1126,43 +1810,40 @@ existing code; using @code{strtol} is more robust. @comment stdlib.h @comment ISO @deftypefun int atoi (const char *@var{string}) -This function is like @code{atol}, except that it returns an @code{int} -value rather than @code{long int}. The @code{atoi} function is also -considered obsolete; use @code{strtol} instead. +This function is like @code{atol}, except that it returns an @code{int}. +The @code{atoi} function is also considered obsolete; use @code{strtol} +instead. @end deftypefun @comment stdlib.h -@comment GNU +@comment ISO @deftypefun {long long int} atoll (const char *@var{string}) This function is similar to @code{atol}, except it returns a @code{long -long int} value rather than @code{long int}. +long int}. -The @code{atoll} function is a GNU extension but it will eventually be -part of the next ISO C standard. +The @code{atoll} function was introduced in @w{ISO C 9x}. It too is +obsolete (despite having just been added); use @code{strtoll} instead. @end deftypefun -The POSIX locales contain some information about how to format numbers -(@pxref{General Numeric}). This mainly deals with representing numbers -for better readability for humans. The functions present so far in this -section cannot handle numbers in this form. - -If this functionality is needed in a program one can use the functions -from the @code{scanf} family which know about the flag @samp{'} for -parsing numeric input (@pxref{Numeric Input Conversions}). Sometimes it -is more desirable to have finer control. - -In these situation one could use the function -@code{__strto@var{XXX}_internal}. @var{XXX} here stands for any of the -above forms. All numeric conversion functions (including the functions -to process floating-point numbers) have such a counterpart. The -difference to the normal form is the extra argument at the end of the -parameter list. If this value has an non-zero value the handling of -number grouping is enabled. The advantage of using these functions is -that the @var{tailptr} parameters allow to determine which part of the -input is processed. The @code{scanf} functions don't provide this -information. The drawback of using these functions is that they are not -portable. They only exist in the GNU C library. - +@c !!! please fact check this paragraph -zw +@findex strtol_l +@findex strtoul_l +@findex strtoll_l +@findex strtoull_l +@cindex parsing numbers and locales +@cindex locales, parsing numbers and +Some locales specify a printed syntax for numbers other than the one +that these functions understand. If you need to read numbers formatted +in some other locale, you can use the @code{strtoX_l} functions. Each +of the @code{strtoX} functions has a counterpart with @samp{_l} added to +its name. The @samp{_l} counterparts take an additional argument: a +pointer to an @code{locale_t} structure, which describes how the numbers +to be read are formatted. @xref{Locales}. + +@strong{Portability Note:} These functions are all GNU extensions. You +can also use @code{scanf} or its relatives, which have the @samp{'} flag +for parsing numeric input according to the current locale +(@pxref{Numeric Input Conversions}). This feature is standard. Here is a function which parses a string as a sequence of integers and returns the sum of them: @@ -1249,78 +1930,40 @@ In a locale other than the standard @code{"C"} or @code{"POSIX"} locales, this function may recognize additional locale-dependent syntax. If the string has valid syntax for a floating-point number but the value -is not representable because of overflow, @code{strtod} returns either -positive or negative @code{HUGE_VAL} (@pxref{Mathematics}), depending on -the sign of the value. Similarly, if the value is not representable -because of underflow, @code{strtod} returns zero. It also sets @code{errno} -to @code{ERANGE} if there was overflow or underflow. - -There are two more special inputs which are recognized by @code{strtod}. -The string @code{"inf"} or @code{"infinity"} (without consideration of -case and optionally preceded by a @code{"+"} or @code{"-"} sign) is -changed to the floating-point value for infinity if the floating-point -format supports this; and to the largest representable value otherwise. - -If the input string is @code{"nan"} or -@code{"nan(@var{n-char-sequence})"} the return value of @code{strtod} is -the representation of the NaN (not a number) value (if the -floating-point format supports this). In the second form the part -@var{n-char-sequence} allows to specify the form of the NaN value in an -implementation specific way. When using the @w{IEEE 754} -floating-point format, the NaN value can have a lot of forms since only -at least one bit in the mantissa must be set. In the GNU C library -implementation of @code{strtod} the @var{n-char-sequence} is interpreted -as a number (as recognized by @code{strtol}, @pxref{Parsing of Integers}). -The mantissa of the return value corresponds to this given number. - -Since the value zero which is returned in the error case is also a valid -result the user should set the global variable @code{errno} to zero -before calling this function. So one can test for failures after the -call since all failures set @code{errno} to a non-zero value. +is outside the range of a @code{double}, @code{strtod} will signal +overflow or underflow as described in @ref{Math Error Reporting}. + +@code{strtod} recognizes four special input strings. The strings +@code{"inf"} and @code{"infinity"} are converted to @math{@infinity{}}, +or to the largest representable value if the floating-point format +doesn't support infinities. You can prepend a @code{"+"} or @code{"-"} +to specify the sign. Case is ignored when scanning these strings. + +The strings @code{"nan"} and @code{"nan(@var{chars...})"} are converted +to NaN. Again, case is ignored. If @var{chars...} are provided, they +are used in some unspecified fashion to select a particular +representation of NaN (there can be several). + +Since zero is a valid result as well as the value returned on error, you +should check for errors in the same way as for @code{strtol}, by +examining @var{errno} and @var{tailptr}. @end deftypefun @comment stdlib.h @comment GNU @deftypefun float strtof (const char *@var{string}, char **@var{tailptr}) -This function is similar to the @code{strtod} function but it returns a -@code{float} value instead of a @code{double} value. If the precision -of a @code{float} value is sufficient this function should be used since -it is much faster than @code{strtod} on some architectures. The reasons -are obvious: @w{IEEE 754} defines @code{float} to have a mantissa of 23 -bits while @code{double} has 53 bits and every additional bit of -precision can require additional computation. - -If the string has valid syntax for a floating-point number but the value -is not representable because of overflow, @code{strtof} returns either -positive or negative @code{HUGE_VALF} (@pxref{Mathematics}), depending on -the sign of the value. - -This function is a GNU extension. +@deftypefunx {long double} strtold (const char *@var{string}, char **@var{tailptr}) +These functions are analogous to @code{strtod}, but return @code{float} +and @code{long double} values respectively. They report errors in the +same way as @code{strtod}. @code{strtof} can be substantially faster +than @code{strtod}, but has less precision; conversely, @code{strtold} +can be much slower but has more precision (on systems where @code{long +double} is a separate type). + +These functions are GNU extensions. @end deftypefun @comment stdlib.h -@comment GNU -@deftypefun {long double} strtold (const char *@var{string}, char **@var{tailptr}) -This function is similar to the @code{strtod} function but it returns a -@code{long double} value instead of a @code{double} value. It should be -used when high precision is needed. On systems which define a @code{long -double} type (i.e., on which it is not the same as @code{double}) -running this function might take significantly more time since more bits -of precision are required. - -If the string has valid syntax for a floating-point number but the value -is not representable because of overflow, @code{strtold} returns either -positive or negative @code{HUGE_VALL} (@pxref{Mathematics}), depending on -the sign of the value. - -This function is a GNU extension. -@end deftypefun - -As for the integer parsing functions there are additional functions -which will handle numbers represented using the grouping scheme of the -current locale (@pxref{Parsing of Integers}). - -@comment stdlib.h @comment ISO @deftypefun double atof (const char *@var{string}) This function is similar to the @code{strtod} function, except that it @@ -1329,168 +1972,140 @@ is provided mostly for compatibility with existing code; using @code{strtod} is more robust. @end deftypefun +The GNU C library also provides @samp{_l} versions of thse functions, +which take an additional argument, the locale to use in conversion. +@xref{Parsing of Integers}. -@node Old-style number conversion -@section Old-style way of converting numbers to strings +@node System V Number Conversion +@section Old-fashioned System V number-to-string functions -The @w{System V} library provided three functions to convert numbers to -strings which have a unusual and hard-to-be-used semantic. The GNU C -library also provides these functions together with some useful -extensions in the same sense. +The old @w{System V} C library provided three functions to convert +numbers to strings, with unusual and hard-to-use semantics. The GNU C +library also provides these functions and some natural extensions. -Generally, you should avoid using these functions unless the really fit -into the problem you have to solve. Otherwise it is almost always -better to use @code{sprintf} since its greater availability (it is an -@w{ISO C} function). +These functions are only available in glibc and on systems descended +from AT&T Unix. Therefore, unless these functions do precisely what you +need, it is better to use @code{sprintf}, which is standard. +All these functions are defined in @file{stdlib.h}. @comment stdlib.h @comment SVID, Unix98 -@deftypefun {char *} ecvt (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{sign}) +@deftypefun {char *} ecvt (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}) The function @code{ecvt} converts the floating-point number @var{value} -to a string with at most @var{ndigit} decimal digits. If @code{ndigit} -is greater than the accuracy of the @code{double} floating-point type -the implementation can shorten @var{ndigit} to a reasonable value. The -returned string neither contains decimal point nor sign. The high-order +to a string with at most @var{ndigit} decimal digits. +The returned string contains no decimal point or sign. The first digit of the string is non-zero (unless @var{value} is actually zero) -and the low-order digit is rounded. The variable pointed to by -@var{decpt} gets the position of the decimal character relative to the -start of the string. If @var{value} is negative, @var{sign} is set to a -non-zero value, otherwise to 0. +and the last digit is rounded to nearest. @var{decpt} is set to the +index in the string of the first digit after the decimal point. +@var{neg} is set to a nonzero value if @var{value} is negative, zero +otherwise. The returned string is statically allocated and overwritten by each call to @code{ecvt}. -If @var{value} is zero, it's implementation defined if @var{decpt} is +If @var{value} is zero, it's implementation defined whether @var{decpt} is @code{0} or @code{1}. -The prototype for this function can be found in @file{stdlib.h}. +For example: @code{ecvt (12.3, 5, &decpt, &neg)} returns @code{"12300"} +and sets @var{decpt} to @code{2} and @var{neg} to @code{0}. @end deftypefun -As an example @code{ecvt (12.3, 5, &decpt, &sign)} returns @code{"12300"} -and sets @var{decpt} to @code{2} and @var{sign} to @code{0}. - @comment stdlib.h @comment SVID, Unix98 -@deftypefun {char *} fcvt (double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{sign}) -The function @code{fcvt} is similar to @code{ecvt} with the difference -that @var{ndigit} specifies the digits after the decimal point. If -@var{ndigit} is less than zero, @var{value} is rounded to the left of -the decimal point upto the reasonable limit (e.g., @math{123.45} is only -rounded to the third digit before the decimal point, even if -@var{ndigit} is less than @math{-3}). +@deftypefun {char *} fcvt (double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{neg}) +The function @code{fcvt} is like @code{ecvt}, but @var{ndigit} specifies +the number of digits after the decimal point. If @var{ndigit} is less +than zero, @var{value} is rounded to the @math{@var{ndigit}+1}'th place to the +left of the decimal point. For example, if @var{ndigit} is @code{-1}, +@var{value} will be rounded to the nearest 10. If @var{ndigit} is +negative and larger than the number of digits to the left of the decimal +point in @var{value}, @var{value} will be rounded to one significant digit. The returned string is statically allocated and overwritten by each call to @code{fcvt}. - -The prototype for this function can be found in @file{stdlib.h}. @end deftypefun @comment stdlib.h @comment SVID, Unix98 @deftypefun {char *} gcvt (double @var{value}, int @var{ndigit}, char *@var{buf}) -The @code{gcvt} function also converts @var{value} to a NUL terminated -string but in a way similar to the @code{%g} format of -@code{sprintf}. It also does not use a static buffer but instead uses -the user-provided buffer starting at @var{buf}. It is the user's -responsibility to make sure the buffer is long enough to contain the -result. Unlike the @code{ecvt} and @code{fcvt} functions @code{gcvt} -includes the sign and the decimal point characters (which are determined -according to the current locale) in the result. Therefore there are yet -less reasons to use this function instead of @code{sprintf}. - -The return value is @var{buf}. - -The prototype for this function can be found in @file{stdlib.h}. +@code{gcvt} is functionally equivalent to @samp{sprintf(buf, "%*g", +ndigit, value}. It is provided only for compatibility's sake. It +returns @var{buf}. @end deftypefun - -All three functions have in common that they use @code{double} -values as parameter. Calling these functions using @code{long -double} values would mean a loss of precision due to the implicit -rounding. Therefore the GNU C library contains three more functions -with similar semantics which take @code{long double} values. +As extensions, the GNU C library provides versions of these three +functions that take @code{long double} arguments. @comment stdlib.h @comment GNU -@deftypefun {char *} qecvt (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{sign}) -This function is equivalent to the @code{ecvt} function except that it -takes an @code{long double} value for the first parameter. - -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +@deftypefun {char *} qecvt (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}) +This function is equivalent to @code{ecvt} except that it +takes a @code{long double} for the first parameter. @end deftypefun @comment stdlib.h @comment GNU -@deftypefun {char *} qfcvt (long double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{sign}) -This function is equivalent to the @code{fcvt} function except that it -takes an @code{long double} value for the first parameter. - -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +@deftypefun {char *} qfcvt (long double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{neg}) +This function is equivalent to @code{fcvt} except that it +takes a @code{long double} for the first parameter. @end deftypefun @comment stdlib.h @comment GNU @deftypefun {char *} qgcvt (long double @var{value}, int @var{ndigit}, char *@var{buf}) -This function is equivalent to the @code{gcvt} function except that it -takes an @code{long double} value for the first parameter. - -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +This function is equivalent to @code{gcvt} except that it +takes a @code{long double} for the first parameter. @end deftypefun @cindex gcvt_r -As said above the @code{ecvt} and @code{fcvt} function along with their -@code{long double} equivalents have the problem that they return a value -located in a static buffer which is overwritten by the next call of the -function. This limitation is lifted in yet another set of functions -which also are GNU extensions. These reentrant functions can be -recognized by the by the conventional @code{_r} ending. Obviously there -is no need for a @code{gcvt_r} function. +The @code{ecvt} and @code{fcvt} functions, and their @code{long double} +equivalents, all return a string located in a static buffer which is +overwritten by the next call to the function. The GNU C library +provides another set of extended functions which write the converted +string into a user-supplied buffer. These have the conventional +@code{_r} suffix. + +@code{gcvt_r} is not necessary, because @code{gcvt} already uses a +user-supplied buffer. @comment stdlib.h @comment GNU -@deftypefun {char *} ecvt_r (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{sign}, char *@var{buf}, size_t @var{len}) -The @code{ecvt_r} function is similar to the @code{ecvt} function except -that it places its result into the user-specified buffer starting at -@var{buf} with length @var{len}. +@deftypefun {char *} ecvt_r (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len}) +The @code{ecvt_r} function is the same as @code{ecvt}, except +that it places its result into the user-specified buffer pointed to by +@var{buf}, with length @var{len}. -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +This function is a GNU extension. @end deftypefun @comment stdlib.h @comment SVID, Unix98 -@deftypefun {char *} fcvt_r (double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{sign}, char *@var{buf}, size_t @var{len}) -The @code{fcvt_r} function is similar to the @code{fcvt} function except -that it places its result into the user-specified buffer starting at -@var{buf} with length @var{len}. +@deftypefun {char *} fcvt_r (double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len}) +The @code{fcvt_r} function is the same as @code{fcvt}, except +that it places its result into the user-specified buffer pointed to by +@var{buf}, with length @var{len}. -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +This function is a GNU extension. @end deftypefun @comment stdlib.h @comment GNU -@deftypefun {char *} qecvt_r (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{sign}, char *@var{buf}, size_t @var{len}) -The @code{qecvt_r} function is similar to the @code{qecvt} function except -that it places its result into the user-specified buffer starting at -@var{buf} with length @var{len}. +@deftypefun {char *} qecvt_r (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len}) +The @code{qecvt_r} function is the same as @code{qecvt}, except +that it places its result into the user-specified buffer pointed to by +@var{buf}, with length @var{len}. -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +This function is a GNU extension. @end deftypefun @comment stdlib.h @comment GNU -@deftypefun {char *} qfcvt_r (long double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{sign}, char *@var{buf}, size_t @var{len}) -The @code{qfcvt_r} function is similar to the @code{qfcvt} function except -that it places its result into the user-specified buffer starting at -@var{buf} with length @var{len}. +@deftypefun {char *} qfcvt_r (long double @var{value}, int @var{ndigit}, int @var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len}) +The @code{qfcvt_r} function is the same as @code{qfcvt}, except +that it places its result into the user-specified buffer pointed to by +@var{buf}, with length @var{len}. -This function is a GNU extension. The prototype can be found in -@file{stdlib.h}. +This function is a GNU extension. @end deftypefun diff --git a/manual/chapters.texi b/manual/chapters.texi new file mode 100644 index 0000000..a5a8a57 --- /dev/null +++ b/manual/chapters.texi @@ -0,0 +1,35 @@ +@include intro.texi +@include errno.texi +@include memory.texi +@include ctype.texi +@include string.texi +@include mbyte.texi +@include locale.texi +@include message.texi +@include search.texi +@include pattern.texi +@include io.texi +@include stdio.texi +@include llio.texi +@include filesys.texi +@include pipe.texi +@include socket.texi +@include terminal.texi +@include math.texi +@include arith.texi +@include time.texi +@include setjmp.texi +@include signal.texi +@include startup.texi +@include process.texi +@include job.texi +@include nss.texi +@include users.texi +@include sysinfo.texi +@include conf.texi +@include ../linuxthreads/linuxthreads.texi +@include lang.texi +@include header.texi +@include install.texi +@include maint.texi +@include contrib.texi diff --git a/manual/conf.texi b/manual/conf.texi index 529c3ad..eabbce6 100644 --- a/manual/conf.texi +++ b/manual/conf.texi @@ -1,4 +1,6 @@ -@node System Configuration, Language Features, System Information, Top +@c This node must have no next pointer. +@node System Configuration, , System Information, Top +@c %MENU% Parameters describing operating system limits @chapter System Configuration Parameters The functions and macros listed in this chapter give information about diff --git a/manual/contrib.texi b/manual/contrib.texi index 11c0dd2..84362cb 100644 --- a/manual/contrib.texi +++ b/manual/contrib.texi @@ -1,4 +1,5 @@ @node Contributors, Copying, Maintenance, Top +@c %MENU% Who wrote what parts of the GNU C library @appendix Contributors to the GNU C Library The GNU C library was written originally by Roland McGrath, and is diff --git a/manual/ctype.texi b/manual/ctype.texi index 8e8db4a..26e40a1 100644 --- a/manual/ctype.texi +++ b/manual/ctype.texi @@ -1,4 +1,5 @@ @node Character Handling, String and Array Utilities, Memory Allocation, Top +@c %MENU% Character testing and conversion functions @chapter Character Handling Programs that work with characters and strings often need to classify a diff --git a/manual/errno.texi b/manual/errno.texi index f006bf7..e0c5b87 100644 --- a/manual/errno.texi +++ b/manual/errno.texi @@ -1,5 +1,6 @@ @node Error Reporting, Memory Allocation, Introduction, Top @chapter Error Reporting +@c %MENU% How library functions report errors @cindex error reporting @cindex reporting errors @cindex error codes diff --git a/manual/filesys.texi b/manual/filesys.texi index ddb0286..5d6df0a 100644 --- a/manual/filesys.texi +++ b/manual/filesys.texi @@ -1,4 +1,5 @@ @node File System Interface, Pipes and FIFOs, Low-Level I/O, Top +@c %MENU% Functions for manipulating files @chapter File System Interface This chapter describes the GNU C library's functions for manipulating diff --git a/manual/header.texi b/manual/header.texi index b6ca60e..0ab36d7 100644 --- a/manual/header.texi +++ b/manual/header.texi @@ -1,4 +1,5 @@ @node Library Summary, Installation, Language Features, Top +@c %MENU% A summary showing the syntax, header file, and derivation of each library feature @appendix Summary of Library Facilities This appendix is a complete list of the facilities declared within the diff --git a/manual/install.texi b/manual/install.texi index 716c2b9..00b4cbe 100644 --- a/manual/install.texi +++ b/manual/install.texi @@ -3,6 +3,7 @@ @setfilename INSTALL @node Installation, Maintenance, Library Summary, Top +@c %MENU% How to install the GNU C library @appendix Installing the GNU C Library @menu diff --git a/manual/intro.texi b/manual/intro.texi index fa16041..3d674ac 100644 --- a/manual/intro.texi +++ b/manual/intro.texi @@ -1,5 +1,6 @@ @node Introduction, Error Reporting, Top, Top @chapter Introduction +@c %MENU% Purpose of the GNU C Library The C language provides no built-in facilities for performing such common operations as input/output, memory management, string diff --git a/manual/io.texi b/manual/io.texi index e43685f..34fb352 100644 --- a/manual/io.texi +++ b/manual/io.texi @@ -1,4 +1,5 @@ @node I/O Overview, I/O on Streams, Pattern Matching, Top +@c %MENU% Introduction to the I/O facilities @chapter Input/Output Overview Most programs need to do either input (reading data) or output (writing diff --git a/manual/job.texi b/manual/job.texi index 342aee3..44b8783 100644 --- a/manual/job.texi +++ b/manual/job.texi @@ -1,4 +1,5 @@ -@node Job Control +@node Job Control, Name Service Switch, Processes, Top +@c %MENU% All about process groups and sessions @chapter Job Control @cindex process groups diff --git a/manual/lang.texi b/manual/lang.texi index 889bda3..ff80e16 100644 --- a/manual/lang.texi +++ b/manual/lang.texi @@ -1,4 +1,6 @@ -@node Language Features, Library Summary, System Configuration, Top +@c This node must not have a prev pointer. +@node Language Features, Library Summary, , Top +@c %MENU% C language features provided by the library @appendix C Language Facilities in the Library Some of the facilities implemented by the C library really should be diff --git a/manual/libc-texinfo.sh b/manual/libc-texinfo.sh new file mode 100644 index 0000000..88733cb --- /dev/null +++ b/manual/libc-texinfo.sh @@ -0,0 +1,115 @@ +#! /bin/sh + +# Create libc.texinfo from the chapter files. + +grep '^@node.*Top' $1 | cut -d, -f-2 | + sed 's/, /:/; s/:@node /:/; s/ /_/g; s/:/ /g' >cnodes.$$ + +$AWK '{ file[$2] = $1; nnode[$2] = $3 } +END { for(x in file) + if(file[x] != "") + print file[x] ":" x, file[nnode[x]] ":" nnode[x] }' \ + cnodes.$$ | tsort | sed 's/_/ /g; $d' >corder.$$ + +[ -z "$2" ] || grep '^@node.*Top' `echo $2 /dev/null | tr ' ' '\n' | sort` | + cut -d, -f1 | sed 's/@node //' >xorder.$$ + +grep '^@node.*Top' $3 | cut -d, -f-2 | + sed 's/, /:/; s/:@node /:/; s/ /_/g; s/:/ /g' >anodes.$$ + +$AWK '{ file[$2] = $1; nnode[$2] = $3 } +END { for(x in file) + if(file[x] != "") + print file[x] ":" x, file[nnode[x]] ":" nnode[x] }' \ + anodes.$$ | tsort | sed 's/_/ /g; $d' >aorder.$$ + +IFS=: + +>incl.$$ +>smenu.$$ +>lmenu.$$ + +while read file node; do + echo "@include $file" >>incl.$$ + echo "* $node:: `sed -n 's/^@c %MENU% //p' $file`" >>smenu.$$ + lmenu=`sed -n '/^@menu/,/^@end menu/p; /^@end menu/q' $file | + sed '/^@menu/d; /^@end menu/d'` + [ -z "$lmenu" ] || ( + echo; echo "$node"; echo + echo "$lmenu" + ) >>lmenu.$$ +done >smenu.$$ + + while read file node; do + echo "@include $file" >>incl.$$ + echo "* $node:: `sed -n 's/^@c %MENU% //p' $file`" >>smenu.$$ + lmenu=`sed -n '/^@menu/,/^@end menu/p; /^@end menu/q' $file | + sed '/^@menu/d; /^@end menu/d'` + [ -z "$lmenu" ] || ( + echo; echo "$node"; echo + echo "$lmenu" + ) >>lmenu.$$ + done >smenu.$$ + +while read file node; do + echo "@include $file" >>incl.$$ + echo "* $node:: `sed -n 's/^@c %MENU% //p' $file`" >>smenu.$$ + lmenu=`sed -n '/^@menu/,/^@end menu/p; /^@end menu/q' $file | + sed '/^@menu/d; /^@end menu/d'` + [ -z "$lmenu" ] || ( + echo; echo "$node"; echo + echo "$lmenu" + ) >>lmenu.$$ +done 78) { + printf("\n%34s", ""); + hpos = 35 + length(word[i]); + } + printf(" %s", word[i]); + } + print "."; +} + +!/^\*/ { print; } +' smenu.$$ >smenux.$$ + +mv -f incl.$$ chapters.texi + +(echo '@menu' + cat smenux.$$ + cat <top-menu.texi.$$ +mv -f top-menu.texi.$$ top-menu.texi + +rm -f *.$$ diff --git a/manual/libc.texinfo b/manual/libc.texinfo index 1e92d52..0beec66 100644 --- a/manual/libc.texinfo +++ b/manual/libc.texinfo @@ -109,896 +109,8 @@ This is Edition @value{EDITION}, last updated @value{UPDATED}, of of the GNU C Library. @end ifinfo - -@menu -* Introduction:: Purpose of the GNU C Library. -* Error Reporting:: How the GNU Library functions report - error conditions. -* Memory Allocation:: Your program can allocate memory dynamically - and manipulate it via pointers. -* Character Handling:: Character testing and conversion functions. -* String and Array Utilities:: Utilities for copying and comparing - strings and arrays. -* Extended Characters:: Support for extended character sets. -* Locales:: The country and language can affect - the behavior of library functions. -* Message Translation:: How to make the program speak the users - language. -* Searching and Sorting:: General searching and sorting functions. -* Pattern Matching:: Matching wildcards and regular expressions, - and shell-style ``word expansion''. -* I/O Overview:: Introduction to the I/O facilities. -* Streams: I/O on Streams. High-level, portable I/O facilities. -* Low-Level I/O:: Low-level, less portable I/O. -* File System Interface:: Functions for manipulating files. -* Pipes and FIFOs:: A simple interprocess communication mechanism. -* Sockets:: A more complicated interprocess communication - mechanism, with support for networking. -* Low-Level Terminal Interface::How to change the characteristics - of a terminal device. -* Mathematics:: Math functions (transcendental functions, - random numbers, absolute value, etc.). -* Arithmetic:: Low-level arithmetic functions. -* Date and Time:: Functions for getting the date and time, - and for conversion between formats. -* Non-Local Exits:: The @code{setjmp} and @code{longjmp} facilities. -* Signal Handling:: All about signals; how to send them, - block them, and handle them. -* Process Startup:: Writing the beginning and end of your program. -* Processes:: How to create processes and run other programs. -* Job Control:: All about process groups and sessions. -* Name Service Switch:: Accessing the various system databases. -* Users and Groups:: How users are identified and classified. -* System Information:: Getting information about the - hardware and software configuration - of the machine a program runs on. -* System Configuration:: Parameters describing operating system limits. - -Appendices - -* Language Features:: C language features provided by the library. - -* Library Summary:: A summary showing the syntax, header file, - and derivation of each library feature. -* Installation:: How to install the GNU C library. -* Maintenance:: How to enhance and port the GNU C Library. -* Contributors:: Who wrote what parts of the GNU C Library. -* Copying:: The GNU Library General Public License says - how you can copy and share the GNU C Library. - -Indices - -* Concept Index:: Index of concepts and names. -* Type Index:: Index of types and type qualifiers. -* Function Index:: Index of functions and function-like macros. -* Variable Index:: Index of variables and variable-like macros. -* File Index:: Index of programs and files. - - --- The Detailed Node Listing --- - -Introduction - -* Getting Started:: Getting Started -* Standards and Portability:: Standards and Portability -* Using the Library:: Using the Library -* Roadmap to the Manual:: Roadmap to the Manual - -Standards and Portability - -* ISO C:: The American National Standard for the - C programming language. -* POSIX:: The ISO/IEC 9945 (aka IEEE 1003) standards - for operating systems. -* Berkeley Unix:: BSD and SunOS. -* SVID:: The System V Interface Description. - -Using the Library - -* Header Files:: How to use the header files in your programs. -* Macro Definitions:: Some functions in the library may really - be implemented as macros. -* Reserved Names:: The C standard reserves some names for - the library, and some for users. -* Feature Test Macros:: How to control what names are defined. - -Error Reporting - -* Checking for Errors:: How errors are reported by library functions. -* Error Codes:: What all the error codes are. -* Error Messages:: Mapping error codes onto error messages. - -Memory Allocation - -* Memory Concepts:: An introduction to concepts and terminology. -* Dynamic Allocation and C:: How to get different kinds of allocation in C. -* Unconstrained Allocation:: The @code{malloc} facility allows fully general - dynamic allocation. -* Obstacks:: Obstacks are less general than malloc - but more efficient and convenient. -* Variable Size Automatic:: Allocation of variable-sized blocks - of automatic storage that are freed when the - calling function returns. -* Relocating Allocator:: Waste less memory, if you can tolerate - automatic relocation of the blocks you get. - -Unconstrained Allocation - -* Basic Allocation:: Simple use of @code{malloc}. -* Malloc Examples:: Examples of @code{malloc}. @code{xmalloc}. -* Freeing after Malloc:: Use @code{free} to free a block you - got with @code{malloc}. -* Changing Block Size:: Use @code{realloc} to make a block - bigger or smaller. -* Allocating Cleared Space:: Use @code{calloc} to allocate a - block and clear it. -* Efficiency and Malloc:: Efficiency considerations in use of - these functions. -* Aligned Memory Blocks:: Allocating specially aligned memory: - @code{memalign} and @code{valloc}. -* Heap Consistency Checking:: Automatic checking for errors. -* Hooks for Malloc:: You can use these hooks for debugging - programs that use @code{malloc}. -* Statistics of Malloc:: Getting information about how much - memory your program is using. -* Summary of Malloc:: Summary of @code{malloc} and related functions. - -Obstacks - -* Creating Obstacks:: How to declare an obstack in your program. -* Preparing for Obstacks:: Preparations needed before you can - use obstacks. -* Allocation in an Obstack:: Allocating objects in an obstack. -* Freeing Obstack Objects:: Freeing objects in an obstack. -* Obstack Functions:: The obstack functions are both - functions and macros. -* Growing Objects:: Making an object bigger by stages. -* Extra Fast Growing:: Extra-high-efficiency (though more - complicated) growing objects. -* Status of an Obstack:: Inquiries about the status of an obstack. -* Obstacks Data Alignment:: Controlling alignment of objects in obstacks. -* Obstack Chunks:: How obstacks obtain and release chunks. - Efficiency considerations. -* Summary of Obstacks:: - -Automatic Storage with Variable Size - -* Alloca Example:: Example of using @code{alloca}. -* Advantages of Alloca:: Reasons to use @code{alloca}. -* Disadvantages of Alloca:: Reasons to avoid @code{alloca}. -* GNU C Variable-Size Arrays:: Only in GNU C, here is an alternative - method of allocating dynamically and - freeing automatically. -Relocating Allocator - -* Relocator Concepts:: How to understand relocating allocation. -* Using Relocator:: Functions for relocating allocation. - -Character Handling - -* Classification of Characters::Testing whether characters are - letters, digits, punctuation, etc. -* Case Conversion:: Case mapping, and the like. - -String and Array Utilities - -* Representation of Strings:: Introduction to basic concepts. -* String/Array Conventions:: Whether to use a string function or an - arbitrary array function. -* String Length:: Determining the length of a string. -* Copying and Concatenation:: Functions to copy the contents of strings - and arrays. -* String/Array Comparison:: Functions for byte-wise and character-wise - comparison. -* Collation Functions:: Functions for collating strings. -* Search Functions:: Searching for a specific element or substring. -* Finding Tokens in a String:: Splitting a string into tokens by looking - for delimiters. - -Extended Characters - -* Extended Char Intro:: Multibyte codes versus wide characters. -* Locales and Extended Chars:: The locale selects the character codes. -* Multibyte Char Intro:: How multibyte codes are represented. -* Wide Char Intro:: How wide characters are represented. -* Wide String Conversion:: Converting wide strings to multibyte code - and vice versa. -* Length of Char:: how many bytes make up one multibyte char. -* Converting One Char:: Converting a string character by character. -* Example of Conversion:: Example showing why converting - one character at a time may be useful. -* Shift State:: Multibyte codes with "shift characters". - -Locales and Internationalization - -* Effects of Locale:: Actions affected by the choice of locale. -* Choosing Locale:: How the user specifies a locale. -* Locale Categories:: Different purposes for which - you can select a locale. -* Setting the Locale:: How a program specifies the locale. -* Standard Locales:: Locale names available on all systems. -* Numeric Formatting:: How to format numbers for the chosen locale. - -Message Translation - -* Message catalogs a la X/Open:: The @code{catgets} family of functions. -* The Uniforum approach:: The @code{gettext} family of functions. - -Searching and Sorting - -* Comparison Functions:: Defining how to compare two objects. - Since the sort and search facilities are - general, you have to specify the ordering. -* Array Search Function:: The @code{bsearch} function. -* Array Sort Function:: The @code{qsort} function. -* Search/Sort Example:: An example program. - -Pattern Matching - -* Wildcard Matching:: Matching a wildcard pattern against a single string. -* Globbing:: Finding the files that match a wildcard pattern. -* Regular Expressions:: Matching regular expressions against strings. -* Word Expansion:: Expanding shell variables, nested commands, - arithmetic, and wildcards. - This is what the shell does with shell commands. - -I/O Overview - -* I/O Concepts:: Some basic information and terminology. -* File Names:: How to refer to a file. - -I/O Concepts - -* Streams and File Descriptors:: The GNU Library provides two ways - to access the contents of files. -* File Position:: The number of bytes from the - beginning of the file. - -File Names - -* Directories:: Directories contain entries for files. -* File Name Resolution:: A file name specifies how to look up a file. -* File Name Errors:: Error conditions relating to file names. -* File Name Portability:: File name portability and syntax issues. - -I/O on Streams - -* Streams:: About the data type representing a stream. -* Standard Streams:: Streams to the standard input and output - devices are created for you. -* Opening Streams:: How to create a stream to talk to a file. -* Closing Streams:: Close a stream when you are finished with it. -* Simple Output:: Unformatted output by characters and lines. -* Character Input:: Unformatted input by characters and words. -* Line Input:: Reading a line or a record from a stream. -* Unreading:: Peeking ahead/pushing back input just read. -* Formatted Output:: @code{printf} and related functions. -* Customizing Printf:: You can define new conversion specifiers for - @code{printf} and friends. -* Formatted Input:: @code{scanf} and related functions. -* Block Input/Output:: Input and output operations on blocks of data. -* EOF and Errors:: How you can tell if an I/O error happens. -* Binary Streams:: Some systems distinguish between text files - and binary files. -* File Positioning:: About random-access streams. -* Portable Positioning:: Random access on peculiar ISO C systems. -* Stream Buffering:: How to control buffering of streams. -* Temporary Files:: How to open a temporary file. -* Other Kinds of Streams:: Other Kinds of Streams - -Unreading - -* Unreading Idea:: An explanation of unreading with pictures. -* How Unread:: How to call @code{ungetc} to do unreading. - -Formatted Output - -* Formatted Output Basics:: Some examples to get you started. -* Output Conversion Syntax:: General syntax of conversion specifications. -* Table of Output Conversions:: Summary of output conversions, what they do. -* Integer Conversions:: Details of formatting integers. -* Floating-Point Conversions:: Details of formatting floating-point numbers. -* Other Output Conversions:: Details about formatting of strings, - characters, pointers, and the like. -* Formatted Output Functions:: Descriptions of the actual functions. -* Variable Arguments Output:: @code{vprintf} and friends. -* Parsing a Template String:: What kinds of arguments does - a given template call for? - -Customizing Printf - -* Registering New Conversions:: -* Conversion Specifier Options:: -* Defining the Output Handler:: -* Printf Extension Example:: - -Formatted Input - -* Formatted Input Basics:: Some basics to get you started. -* Input Conversion Syntax:: Syntax of conversion specifications. -* Table of Input Conversions:: Summary of input conversions and what they do. -* Numeric Input Conversions:: Details of conversions for reading numbers. -* String Input Conversions:: Details of conversions for reading strings. -* Other Input Conversions:: Details of miscellaneous other conversions. -* Formatted Input Functions:: Descriptions of the actual functions. -* Variable Arguments Input:: @code{vscanf} and friends. - -Stream Buffering - -* Buffering Concepts:: Terminology is defined here. -* Flushing Buffers:: How to ensure that output buffers are flushed. -* Controlling Buffering:: How to specify what kind of buffering to use. - -Other Kinds of Streams - -* String Streams:: -* Custom Streams:: - -Programming Your Own Custom Streams - -* Streams and Cookies:: -* Hook Functions:: - -Low-Level I/O - -* Opening and Closing Files:: How to open and close file descriptors. -* I/O Primitives:: Reading and writing data. -* File Position Primitive:: Setting a descriptor's file position. -* Descriptors and Streams:: Converting descriptor to stream or vice-versa. -* Stream/Descriptor Precautions:: Precautions needed if you use both - descriptors and streams. -* Waiting for I/O:: How to check for input or output - on multiple file descriptors. -* Control Operations:: Various other operations on file descriptors. -* Duplicating Descriptors:: Fcntl commands for duplicating descriptors. -* Descriptor Flags:: Fcntl commands for manipulating flags - associated with file descriptors. -* File Status Flags:: Fcntl commands for manipulating flags - associated with open files. -* File Locks:: Fcntl commands for implementing file locking. -* Interrupt Input:: Getting a signal when input arrives. - -File System Interface - -* Working Directory:: This is used to resolve relative file names. -* Accessing Directories:: Finding out what files a directory contains. -* Hard Links:: Adding alternate names to a file. -* Symbolic Links:: A file that ``points to'' a file name. -* Deleting Files:: How to delete a file, and what that means. -* Renaming Files:: Changing a file's name. -* Creating Directories:: A system call just for creating a directory. -* File Attributes:: Attributes of individual files. -* Making Special Files:: How to create special files. - -Accessing Directories - -* Directory Entries:: Format of one directory entry. -* Opening a Directory:: How to open a directory stream. -* Reading/Closing Directory:: How to read directory entries from the stream. -* Simple Directory Lister:: A very simple directory listing program. -* Random Access Directory:: Rereading part of the directory - already read with the same stream. - -File Attributes - -* Attribute Meanings:: The names of the file attributes, - and what their values mean. -* Reading Attributes:: How to read the attributes of a file. -* Testing File Type:: Distinguishing ordinary files, - directories, links... -* File Owner:: How ownership for new files is determined, - and how to change it. -* Permission Bits:: How information about a file's access mode - is stored. -* Access Permission:: How the system decides who can access a file. -* Setting Permissions:: How permissions for new files are assigned, - and how to change them. -* Testing File Access:: How to find out if your process can - access a file. -* File Times:: About the time attributes of a file. - -Pipes and FIFOs - -* Creating a Pipe:: Making a pipe with the @code{pipe} function. -* Pipe to a Subprocess:: Using a pipe to communicate with a child. -* FIFO Special Files:: Making a FIFO special file. - -Sockets - -* Socket Concepts:: Basic concepts you need to know about. -* Communication Styles:: Stream communication, datagrams, and others. -* Socket Addresses:: How socket names (``addresses'') work. -* Local Namespace:: Details about the local namespace. -* Internet Namespace:: Details about the Internet namespace. -* Open/Close Sockets:: Creating sockets and destroying them. -* Connections:: Operations on sockets with connection state. -* Datagrams:: Operations on datagram sockets. -* Socket Options:: Miscellaneous low-level socket options. -* Networks Database:: Accessing the database of network names. - -Socket Addresses - -* Address Formats:: About @code{struct sockaddr}. -* Setting Address:: Binding an address to a socket. -* Reading Address:: Reading the address of a socket. - -Internet Domain - -* Internet Address Formats:: How socket addresses are specified in the - Internet namespace. -* Host Addresses:: All about host addresses of Internet hosts. -* Protocols Database:: Referring to protocols by name. -* Services Database:: Ports may have symbolic names. -* Byte Order:: Different hosts may use different byte - ordering conventions; you need to - canonicalize host address and port number. -* Inet Example:: Putting it all together. - -Host Addresses - -* Abstract Host Addresses:: What a host number consists of. -* Data type: Host Address Data Type. Data type for a host number. -* Functions: Host Address Functions. Functions to operate on them. -* Names: Host Names. Translating host names to host numbers. - -Open/Close Sockets - -* Creating a Socket:: How to open a socket. -* Closing a Socket:: How to close a socket. -* Socket Pairs:: These are created like pipes. - -Connections - -* Connecting:: What the client program must do. -* Listening:: How a server program waits for requests. -* Accepting Connections:: What the server does when it gets a request. -* Who is Connected:: Getting the address of the - other side of a connection. -* Transferring Data:: How to send and receive data. -* Byte Stream Example:: An example client for communicating over a - byte stream socket in the Internet namespace. -* Server Example:: A corresponding server program. -* Out-of-Band Data:: This is an advanced feature. - -Transferring Data - -* Sending Data:: Sending data with @code{write}. -* Receiving Data:: Reading data with @code{read}. -* Socket Data Options:: Using @code{send} and @code{recv}. - -Datagrams - -* Sending Datagrams:: Sending packets on a datagram socket. -* Receiving Datagrams:: Receiving packets on a datagram socket. -* Datagram Example:: An example program: packets sent over a - datagram stream in the local namespace. -* Example Receiver:: Another program, that receives those packets. - -Socket Options - -* Socket Option Functions:: The basic functions for setting and getting - socket options. -* Socket-Level Options:: Details of the options at the socket level. - -Low-Level Terminal Interface - -* Is It a Terminal:: How to determine if a file is a terminal - device, and what its name is. -* I/O Queues:: About flow control and typeahead. -* Canonical or Not:: Two basic styles of input processing. -* Terminal Modes:: How to examine and modify flags controlling - terminal I/O: echoing, signals, editing. -* Line Control:: Sending break sequences, clearing buffers... -* Noncanon Example:: How to read single characters without echo. - -Terminal Modes - -* Mode Data Types:: The data type @code{struct termios} and related types. -* Mode Functions:: Functions to read and set terminal attributes. -* Setting Modes:: The right way to set attributes reliably. -* Input Modes:: Flags controlling low-level input handling. -* Output Modes:: Flags controlling low-level output handling. -* Control Modes:: Flags controlling serial port behavior. -* Local Modes:: Flags controlling high-level input handling. -* Line Speed:: How to read and set the terminal line speed. -* Special Characters:: Characters that have special effects, - and how to change them. -* Noncanonical Input:: Controlling how long to wait for input. - -Special Characters - -* Editing Characters:: -* Signal Characters:: -* Start/Stop Characters:: - -Mathematics - -* Domain and Range Errors:: How overflow conditions and the - like are reported. -* Not a Number:: Making NANs and testing for NANs. -* Trig Functions:: Sine, cosine, and tangent. -* Inverse Trig Functions:: Arc sine, arc cosine, and arc tangent. -* Exponents and Logarithms:: Also includes square root. -* Hyperbolic Functions:: Hyperbolic sine and friends. -* Pseudo-Random Numbers:: Functions for generating pseudo-random numbers. -* Absolute Value:: Absolute value functions. - -Pseudo-Random Numbers - -* ISO Random:: @code{rand} and friends. -* BSD Random:: @code{random} and friends. - -Low-Level Arithmetic Functions - -* Normalization Functions:: Hacks for radix-2 representations. -* Rounding and Remainders:: Determining the integer and - fractional parts of a float. -* Integer Division:: Functions for performing integer division. -* Parsing of Numbers:: Functions for ``reading'' numbers from strings. -* Predicates on Floats:: Some miscellaneous test functions. - -Parsing of Numbers - -* Parsing of Integers:: Functions for conversion of integer values. -* Parsing of Floats:: Functions for conversion of floating-point. - -Date and Time - -* Processor Time:: Measures processor time used by a program. -* 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. - -Processor Time - -* Basic CPU Time:: The @code{clock} function. -* Detailed CPU Time:: The @code{times} function. - -Calendar Time - -* Simple Calendar Time:: Facilities for manipulating calendar time. -* High-Resolution Calendar:: A time representation with greater precision. -* Broken-down Time:: Facilities for manipulating local time. -* Formatting Date and Time:: Converting times to strings. -* TZ Variable:: How users specify the time zone. -* Time Zone Functions:: Functions to examine or specify the time zone. -* Time Functions Example:: An example program showing use of some of - the time functions. - -Signal Handling - -* Concepts of Signals:: Introduction to the signal facilities. -* Standard Signals:: Particular kinds of signals with standard - names and meanings. -* Signal Actions:: Specifying what happens when a particular - signal is delivered. -* Defining Handlers:: How to write a signal handler function. -* Generating Signals:: How to send a signal to a process. -* Blocking Signals:: Making the system hold signals temporarily. -* Waiting for a Signal:: Suspending your program until a signal arrives. -* Signal Stack:: Using a Separate Signal Stack -* BSD Signal Handling:: Additional functions for backward - compatibility with BSD. - -Basic Concepts of Signals - -* Kinds of Signals:: Some examples of what can cause a signal. -* Signal Generation:: Concepts of why and how signals occur. -* Delivery of Signal:: Concepts of what a signal does to the process. - -Standard Signals - -* Program Error Signals:: Used to report serious program errors. -* Termination Signals:: Used to interrupt and/or terminate the program. -* Alarm Signals:: Used to indicate expiration of timers. -* Asynchronous I/O Signals:: Used to indicate input is available. -* Job Control Signals:: Signals used to support job control. -* Operation Error Signals:: Used to report operational system errors. -* Miscellaneous Signals:: Miscellaneous Signals. -* Signal Messages:: Printing a message describing a signal. - -Specifying Signal Actions - -* Basic Signal Handling:: The simple @code{signal} function. -* Advanced Signal Handling:: The more powerful @code{sigaction} function. -* Signal and Sigaction:: How those two functions interact. -* Sigaction Function Example:: An example of using the sigaction function. -* Flags for Sigaction:: Specifying options for signal handling. -* Initial Signal Actions:: How programs inherit signal actions. - -Defining Signal Handlers - -* Handler Returns:: -* Termination in Handler:: -* Longjmp in Handler:: -* Signals in Handler:: -* Nonreentrancy:: -* Atomic Data Access:: - -Generating Signals - -* Signaling Yourself:: Signaling Yourself -* Signaling Another Process:: Send a signal to another process. -* Permission for kill:: Permission for using @code{kill} -* Kill Example:: Using @code{kill} for Communication - -Blocking Signals - -* Why Block:: The purpose of blocking signals. -* Signal Sets:: How to specify which signals to block. -* Process Signal Mask:: Blocking delivery of signals to your - process during normal execution. -* Testing for Delivery:: Blocking to Test for Delivery of a Signal -* Blocking for Handler:: Blocking additional signals while a - handler is being run. -* Checking for Pending Signals::Checking for Pending Signals -* Remembering a Signal:: How you can get almost the same effect - as blocking a signal, by handling it - and setting a flag to be tested later. - -Waiting for a Signal - -* Using Pause:: The simple way, using @code{pause}. -* Pause Problems:: Why the simple way is often not very good. -* Sigsuspend:: Reliably waiting for a specific signal. - -BSD Signal Handling - -* BSD Handler:: BSD Function to Establish a Handler. -* Blocking in BSD:: BSD Functions for Blocking Signals - -Process Startup and Termination - -* Program Arguments:: Parsing your program's command-line arguments. -* Environment Variables:: How to access parameters inherited from - a parent process. -* Program Termination:: How to cause a process to terminate and - return status information to its parent. - -Program Arguments - -* Argument Syntax:: By convention, options start with a hyphen. -* Parsing Program Arguments:: Ways to parse program options and arguments. - -Parsing Program Arguments - -* Getopt:: Parsing program options using @code{getopt}. -* Argp:: Parsing program options using @code{argp_parse}. -* Suboptions:: Some programs need more detailed options. -* Suboptions Example:: This shows how it could be done for @code{mount}. - -Environment Variables - -* Environment Access:: How to get and set the values of - environment variables. -* Standard Environment:: These environment variables have - standard interpretations. - -Program Termination - -* Normal Termination:: If a program calls @code{exit}, a - process terminates normally. -* Exit Status:: The @code{exit status} provides information - about why the process terminated. -* Cleanups on Exit:: A process can run its own cleanup - functions upon normal termination. -* Aborting a Program:: The @code{abort} function causes - abnormal program termination. -* Termination Internals:: What happens when a process terminates. - - -Child Processes - -* Running a Command:: The easy way to run another program. -* Process Creation Concepts:: An overview of the hard way to do it. -* Process Identification:: How to get the process ID of a process. -* Creating a Process:: How to fork a child process. -* Executing a File:: How to make a child execute another program. -* Process Completion:: How to tell when a child process has completed. -* Process Completion Status:: How to interpret the status value - returned from a child process. -* BSD Wait Functions:: More functions, for backward compatibility. -* Process Creation Example:: A complete example program. - -Job Control - -* Concepts of Job Control :: Concepts of Job Control -* Job Control is Optional:: Not all POSIX systems support job control. -* Controlling Terminal:: How a process gets its controlling terminal. -* Access to the Terminal:: How processes share the controlling terminal. -* Orphaned Process Groups:: Jobs left after the user logs out. -* Implementing a Shell:: What a shell must do to implement job control. -* Functions for Job Control:: Functions to control process groups. - -Implementing a Job Control Shell - -* Data Structures:: Introduction to the sample shell. -* Initializing the Shell:: What the shell must do to take - responsibility for job control. -* Launching Jobs:: Creating jobs to execute commands. -* Foreground and Background:: Putting a job in foreground of background. -* Stopped and Terminated Jobs:: Reporting job status. -* Continuing Stopped Jobs:: How to continue a stopped job in - the foreground or background. -* Missing Pieces:: Other parts of the shell. - -Functions for Job Control - -* Identifying the Terminal:: Determining the controlling terminal's name. -* Process Group Functions:: Functions for manipulating process groups. -* Terminal Access Functions:: Functions for controlling terminal access. - -Name Service Switch - -* NSS Basics:: What is this NSS good for. -* NSS Configuration File:: Configuring NSS. -* NSS Module Internals:: How does it work internally. -* Extending NSS:: What to do to add services or databases. - -Users and Groups - -* User and Group IDs:: Each user and group has a unique numeric ID. -* Process Persona:: The user IDs and group IDs of a process. -* Why Change Persona:: Why a program might need to change - its user and/or group IDs. -* How Change Persona:: Restrictions on changing user and group IDs. -* Reading Persona:: Examining the process's user and group IDs. -* Setting User ID:: -* Setting Groups:: -* Enable/Disable Setuid:: -* Setuid Program Example:: Setuid Program Example -* Tips for Setuid:: -* Who Logged In:: Getting the name of the user who logged in, - or of the real user ID of the current process. - -* User Database:: Functions and data structures for - accessing the user database. -* Group Database:: Functions and data structures for - accessing the group database. -* Database Example:: Example program showing use of database - inquiry functions. - -User Database - -* User Data Structure:: -* Lookup User:: -* Scanning All Users:: Scanning the List of All Users -* Writing a User Entry:: - -Group Database - -* Group Data Structure:: -* Lookup Group:: -* Scanning All Groups:: Scanning the List of All Groups - -System Information - -* Host Identification:: Determining the name of the machine. -* Hardware/Software Type ID:: Determining the hardware type and - operating system type. - -System Configuration Limits - -* General Limits:: Constants and functions that describe - various process-related limits that have - one uniform value for any given machine. -* System Options:: Optional POSIX features. -* Version Supported:: Version numbers of POSIX.1 and POSIX.2. -* Sysconf:: Getting specific configuration values - of general limits and system options. -* Minimums:: Minimum values for general limits. - -* Limits for Files:: Size limitations on individual files. - These can vary between file systems - or even from file to file. -* Options for Files:: Optional features that some files may support. -* File Minimums:: Minimum values for file limits. -* Pathconf:: Getting the limit values for a particular file. - -* Utility Limits:: Capacity limits of POSIX.2 utility programs. -* Utility Minimums:: Minimum allowable values of those limits. - -* String Parameters:: Getting the default search path. - -Library Facilities that are Part of the C Language - -* Consistency Checking:: Using @code{assert} to abort - if something ``impossible'' happens. -* Variadic Functions:: Defining functions with varying - numbers of arguments. -* Null Pointer Constant:: The macro @code{NULL}. -* Important Data Types:: Data types for object sizes. -* Data Type Measurements:: Parameters of data type representations. - -Variadic Functions - -* Why Variadic:: Reasons for making functions take - variable arguments. -* How Variadic:: How to define and call variadic functions. -* Argument Macros:: Detailed specification of the macros - for accessing variable arguments. -* Variadic Example:: A complete example. - -How Variadic Functions are Defined and Used - -* Variadic Prototypes:: How to make a prototype for a function - with variable arguments. -* Receiving Arguments:: Steps you must follow to access the - optional argument values. -* How Many Arguments:: How to decide whether there are more arguments. -* Calling Variadics:: Things you need to know about calling - variable arguments functions. - -Data Type Measurements - -* Width of Type:: How many bits does an integer type hold? -* Range of Type:: What are the largest and smallest values - that an integer type can hold? -* Floating Type Macros:: Parameters that measure floating-point types. -* Structure Measurement:: Getting measurements on structure types. - -Floating Type Macros - -* Floating Point Concepts:: Definitions of terminology. -* Floating Point Parameters:: Dimensions, limits of floating point types. -* IEEE Floating Point:: How one common representation is described. - -Library Maintenance - -* Installation:: How to configure, compile and install - the GNU C library. -* Reporting Bugs:: How to report bugs (if you want to - get them fixed) and other troubles - you may have with the GNU C library. -@c * Traditional C Compatibility:: Using the GNU C library with non-ANSI -@c C compilers. - -Porting the GNU C Library - -* Hierarchy Conventions:: How the @file{sysdeps} hierarchy is - layed out. -* Porting to Unix:: Porting the library to an average - Unix-like system. -@end menu - - -@comment Includes of all the individual chapters. -@include intro.texi -@include errno.texi -@include memory.texi -@include ctype.texi -@include string.texi -@include mbyte.texi -@include locale.texi -@include message.texi -@include search.texi -@include pattern.texi -@include io.texi -@include stdio.texi -@include llio.texi -@include filesys.texi -@include pipe.texi -@include socket.texi -@include terminal.texi -@include math.texi -@include arith.texi -@include time.texi -@include setjmp.texi -@include signal.texi -@include startup.texi -@include process.texi -@include job.texi -@include nss.texi -@include users.texi -@include sysinfo.texi -@include conf.texi - -@comment Includes of the appendices. -@include lang.texi -@include header.texi -@include install.texi -@include maint.texi -@include contrib.texi - +@include top-menu.texi +@include chapters.texi @set lgpl-appendix @node Copying, Concept Index, Contributors, Top diff --git a/manual/llio.texi b/manual/llio.texi index 6387eec..459032e 100644 --- a/manual/llio.texi +++ b/manual/llio.texi @@ -1,4 +1,5 @@ @node Low-Level I/O, File System Interface, I/O on Streams, Top +@c %MENU% Low-level, less portable I/O @chapter Low-Level Input/Output This chapter describes functions for performing low-level input/output diff --git a/manual/locale.texi b/manual/locale.texi index dfc9117..f4fa3a7 100644 --- a/manual/locale.texi +++ b/manual/locale.texi @@ -1,4 +1,5 @@ @node Locales, Message Translation, Extended Characters, Top +@c %MENU% The country and language can affect the behavior of library functions @chapter Locales and Internationalization Different countries and cultures have varying conventions for how to diff --git a/manual/maint.texi b/manual/maint.texi index a7e0cc4..3d8d24f 100644 --- a/manual/maint.texi +++ b/manual/maint.texi @@ -1,4 +1,5 @@ @node Maintenance, Contributors, Installation, Top +@c %MENU% How to enhance and port the GNU C Library @appendix Library Maintenance @menu diff --git a/manual/math.texi b/manual/math.texi index 1991bfb..10b3262 100644 --- a/manual/math.texi +++ b/manual/math.texi @@ -1,739 +1,129 @@ @c We need some definitions here. +@ifclear mult @ifhtml -@set mult · +@set mult · +@set infty ∞ +@set pie π @end ifhtml @iftex @set mult @cdot +@set infty @infty @end iftex @ifclear mult -@set mult x +@set mult * +@set infty oo +@set pie pi @end ifclear @macro mul @value{mult} @end macro -@iftex -@set infty @infty -@end iftex -@ifclear infty -@set infty oo -@end ifclear @macro infinity @value{infty} @end macro +@ifnottex +@macro pi +@value{pie} +@end macro +@end ifnottex +@end ifclear @node Mathematics, Arithmetic, Low-Level Terminal Interface, Top +@c %MENU% Math functions, useful constants, random numbers @chapter Mathematics This chapter contains information about functions for performing mathematical computations, such as trigonometric functions. Most of these functions have prototypes declared in the header file -@file{math.h}. +@file{math.h}. The complex-valued functions are defined in +@file{complex.h}. @pindex math.h - -For all functions which take a single floating-point argument and for -several other functions as well there are three different functions -available for the type @code{double}, @code{float}, and @code{long -double}. The @code{double} versions of the functions are mostly defined -even in the @w{ISO C 89} standard. The @code{float} and @code{long -double} variants are introduced in the numeric extensions for the C -language which are part of the @w{ISO C 9X} standard. - -Which of the three versions of the function should be used depends on -the situation. For most functions and implementation it is true that -speed and precision do not go together. I.e., the @code{float} versions -are normally faster than the @code{double} and @code{long double} -versions. On the other hand the @code{long double} version has the -highest precision. One should always think about the actual needs and -in case of double using @code{double} is a good compromise. - +@pindex complex.h + +All mathematical functions which take a floating-point argument +have three variants, one each for @code{double}, @code{float}, and +@code{long double} arguments. The @code{double} versions are mostly +defined in @w{ISO C 89}. The @code{float} and @code{long double} +versions are from the numeric extensions to C included in @w{ISO C 9X}. + +Which of the three versions of a function should be used depends on the +situation. For most calculations, the @code{float} functions are the +fastest. On the other hand, the @code{long double} functions have the +highest precision. @code{double} is somewhere in between. It is +usually wise to pick the narrowest type that can accomodate your data. +Not all machines have a distinct @code{long double} type; it may be the +same as @code{double}. @menu -* Domain and Range Errors:: Detecting overflow conditions and the like. -* Exceptions in Math Functions:: Signalling exception in math functions. -* Mathematical Constants:: Precise numeric values for often used - constant. -* FP Comparison Functions:: Special functions to compare floating-point - numbers. -* FP Function Optimizations:: Fast code or small code. -* Trig Functions:: Sine, cosine, and tangent. -* Inverse Trig Functions:: Arc sine, arc cosine, and arc tangent. -* Exponents and Logarithms:: Also includes square root. -* Hyperbolic Functions:: Hyperbolic sine and friends. -* Pseudo-Random Numbers:: Functions for generating pseudo-random - numbers. +* Mathematical Constants:: Precise numeric values for often-used + constants. +* Trig Functions:: Sine, cosine, tangent, and friends. +* Inverse Trig Functions:: Arcsine, arccosine, etc. +* Exponents and Logarithms:: Also pow and sqrt. +* Hyperbolic Functions:: sinh, cosh, tanh, etc. +* Special Functions:: Bessel, gamma, erf. +* Pseudo-Random Numbers:: Functions for generating pseudo-random + numbers. +* FP Function Optimizations:: Fast code or small code. @end menu -@node Domain and Range Errors -@section Domain and Range Errors - -@cindex domain error -Many of the functions listed in this chapter are defined mathematically -over a domain that is only a subset of real numbers. For example, the -@code{acos} function is defined over the domain between @code{@minus{}1} and -@code{1}. If you pass an argument to one of these functions that is -outside the domain over which it is defined, the function sets -@code{errno} to @code{EDOM} to indicate a @dfn{domain error}. On -machines that support @w{IEEE 754} floating point, functions reporting -error @code{EDOM} also return a NaN. - -Some of these functions are defined mathematically to result in a -complex value over parts of their domains. The most familiar example of -this is taking the square root of a negative number. The functions in -this chapter take only real arguments and return only real values; -therefore, if the value ought to be nonreal, this is treated as a domain -error. - -@cindex range error -A related problem is that the mathematical result of a function may not -be representable as a floating point number. If magnitude of the -correct result is too large to be represented, the function sets -@code{errno} to @code{ERANGE} to indicate a @dfn{range error}, and -returns a particular very large value (named by the macro -@code{HUGE_VAL}) or its negation (@code{@minus{}HUGE_VAL}). - -If the magnitude of the result is too small, a value of zero is returned -instead. In this case, @code{errno} might or might not be -set to @code{ERANGE}. - -The only completely reliable way to check for domain and range errors is -to set @code{errno} to @code{0} before you call the mathematical function -and test @code{errno} afterward. As a consequence of this use of -@code{errno}, use of the mathematical functions is not reentrant if you -check for errors. - -@c ### This is no longer true. --drepper -@c None of the mathematical functions ever generates signals as a result of -@c domain or range errors. In particular, this means that you won't see -@c @code{SIGFPE} signals generated within these functions. (@xref{Signal -@c Handling}, for more information about signals.) - -@comment math.h -@comment ISO -@deftypevr Macro double HUGE_VAL -An expression representing a particular very large number. On machines -that use @w{IEEE 754}/@w{IEEE 854} floating point format, the value is -``infinity''. On other machines, it's typically the largest positive -number that can be represented. - -The value of this macro is used as the return value from various -mathematical @code{double} returning functions in overflow situations. -@end deftypevr - -@comment math.h -@comment ISO -@deftypevr Macro float HUGE_VALF -This macro is similar to the @code{HUGE_VAL} macro except that it is -used by functions returning @code{float} values. - -This macro is introduced in @w{ISO C 9X}. -@end deftypevr - -@comment math.h -@comment ISO -@deftypevr Macro {long double} HUGE_VALL -This macro is similar to the @code{HUGE_VAL} macro except that it is -used by functions returning @code{long double} values. The value is -only different from @code{HUGE_VAL} if the architecture really supports -@code{long double} values. - -This macro is introduced in @w{ISO C 9X}. -@end deftypevr - - -A special case is the @code{ilogb} function @pxref{Exponents and -Logarithms}. Since the return value is an integer value, one cannot -compare with @code{HUGE_VAL} etc. Therefore two further values are -defined. - -@comment math.h -@comment ISO -@deftypevr Macro int FP_ILOGB0 -This value is returned by @code{ilogb} if the argument is @code{0}. The -numeric value is either @code{INT_MIN} or @code{-INT_MAX}. - -This macro is introduced in @w{ISO C 9X}. -@end deftypevr - -@comment math.h -@comment ISO -@deftypevr Macro int FP_ILOGBNAN -This value is returned by @code{ilogb} if the argument is @code{NaN}. The -numeric value is either @code{INT_MIN} or @code{INT_MAX}. - -This macro is introduced in @w{ISO C 9X}. -@end deftypevr - - -For more information about floating-point representations and limits, -see @ref{Floating Point Parameters}. In particular, the macro -@code{DBL_MAX} might be more appropriate than @code{HUGE_VAL} for many -uses other than testing for an error in a mathematical function. - - -@node Exceptions in Math Functions -@section Exceptions in Math Functions -@cindex exception -@cindex signal - -Due to the restrictions in the size of the floating-point number -representation or the limitation of the input range of certain functions -some of the mathematical operations and functions have to signal -exceptional situations. The @w{IEEE 754} standard specifies which -exceptions have to be supported and how they can be handled. - -@w{IEEE 754} specifies two actions for floating-point exception: taking -a trap or continuing without doing so. If the trap is taken a -(possibly) user defined trap handler is called and this function can -correct the argument or react somehow else on the call. If the trap -handler returns, its return value is taken as the result of the -operation. - -If no trap handler is called each of the known exceptions has a default -action. This consists of setting a corresponding bit in the -floating-point status word to indicate which kind of exception was -raised and to return a default value, which depends on the exception -(see the table below). - -@noindent -The exceptions defined in @w{IEEE 754} are: - -@table @samp -@item Invalid Operation -This exception is raised if the given operands are invalid for the -operation to be performed. Examples are -(see @w{IEEE 754}, @w{section 7}): -@enumerate -@item -Any operation on a signalling NaN. -@item -Addition or subtraction; magnitude subtraction of infinities such as -@math{(+@infinity{}) + (-@infinity{})}. -@item -Multiplication: -@math{0 @mul{} @infinity{}}. - -@item -Division: @math{0/0} or @math{@infinity{}/@infinity{}}. - -@item -Remainder: @math{x} REM @math{y}, where @math{y} is zero or @math{x} is -infinite. -@item -Square root if the operand is less then zero. -@item -Conversion of an internal floating-point number to an integer or to a -decimal string when overflow, infinity, or NaN precludes a faithful -representation in that format and this cannot otherwise be signaled. -@item -Conversion of an unrecognizable input string. -@item -Comparison via predicates involving @math{<} or @math{>}, without -@code{?}, when the operands are @dfn{unordered}. (@math{?>} means the -unordered greater relation, @xref{FP Comparison Functions}). -@end enumerate - -If the exception does not cause a trap handler to be called the result -of the operation is taken as a quiet NaN. - -@item Division by Zero -This exception is raised if the divisor is zero and the dividend is a -finite nonzero number. If no trap occurs the result is either -@math{+@infinity{}} or @math{-@infinity{}}, depending on the -signs of the operands. - -@item Overflow -This exception is signalled whenever the result cannot be represented -as a finite value in the precision format of the destination. If no trap -occurs the result depends on the sign of the intermediate result and the -current rounding mode (@w{IEEE 754}, @w{section 7.3}): -@enumerate -@item -Round to nearest carries all overflows to @math{@infinity{}} -with the sign of the intermediate result. -@item -Round toward @math{0} carries all overflows to the precision's largest -finite number with the sign of the intermediate result. -@item -Round toward @math{-@infinity{}} carries positive overflows to the -precision's largest finite number and carries negative overflows to -@math{-@infinity{}}. - -@item -Round toward @math{@infinity{}} carries negative overflows to the -precision's most negative finite number and carries positive overflows -to @math{@infinity{}}. -@end enumerate - -@item Underflow -The underflow exception is created when an intermediate result is too -small for the operation or if the operations result rounded to the -destination precision causes a loss of accuracy by approximating the -result by denormalized numbers. - -When no trap is installed for the underflow exception, underflow shall -be signaled (via the underflow flag) only when both tininess and loss of -accuracy have been detected. If no trap handler is installed the -operation continues with an inprecise small value or zero if the -destination precision cannot hold the small exact result. - -@item Inexact -This exception is signalled if the rounded result is not exact (such as -computing the square root of two) or the result overflows without an -overflow trap. -@end table - -To control whether an exception causes a trap to occur all @w{IEEE 754} -conformant floating-point implementations (either hardware or software) -have a control word. By setting specific bits for each exception in -this control word the programmer can decide whether a trap is wanted or -not. - -@w{ISO C 9X} introduces a set of function which can be used to control -exceptions. There are functions to manipulate the control word, to -query the status word or to save and restore the whole state of the -floating-point unit. There are also functions to control the rounding -mode used. - -@menu -* Status bit operations:: Manipulate the FP status word. -* FPU environment:: Controlling the status of the FPU. -* Rounding Modes:: Controlling the rounding mode. -@end menu - -@node Status bit operations -@subsection Controlling the FPU status word - -To control the five types of exceptions defined in @w{IEEE 754} some -functions are defined which abstract the interface to the FPU. The -actual implementation can be very different, depending on the underlying -hardware or software. - -To address the single exception the @file{fenv.h} headers defines a -number of macros: - -@vtable @code -@comment fenv.h -@comment ISO -@item FE_INEXACT -Represents the inexact exception iff the FPU supports this exception. -@comment fenv.h -@comment ISO -@item FE_DIVBYZERO -Represents the divide by zero exception iff the FPU supports this exception. -@comment fenv.h -@comment ISO -@item FE_UNDERFLOW -Represents the underflow exception iff the FPU supports this exception. -@comment fenv.h -@comment ISO -@item FE_OVERFLOW -Represents the overflow exception iff the FPU supports this exception. -@comment fenv.h -@comment ISO -@item FE_INVALID -Represents the invalid exception iff the FPU supports this exception. -@end vtable - -The macro @code{FE_ALL_EXCEPT} is the bitwise OR of all exception macros -which are supported by the FP implementation. - -Each of the supported exception flags can either be set or unset. The -@w{ISO C 9X} standard defines functions to set, unset and test the -status of the flags. - -@comment fenv.h -@comment ISO -@deftypefun void feclearexcept (int @var{excepts}) -This function clears all of the supported exception flags denoted by -@var{excepts} in the status word. -@end deftypefun - -To safe the current status of the flags in the status word @file{fenv.h} -defines the type @code{fexcept_t} which can hold all the information. -The following function can be used to retrieve the current setting. - -@comment fenv.h -@comment ISO -@deftypefun void fegetexceptflag (fexcept_t *@var{flagp}, int @var{excepts}) -Store in the variable pointed to by @var{flagp} an -implementation-defined value representing the current setting of the -exception flags indicated by the parameter @var{excepts}. -@end deftypefun - -@noindent -To restore the previously saved values one can use this function: - -@comment fenv.h -@comment ISO -@deftypefun void fesetexceptflag (const fexcept_t *@var{flagp}, int @var{excepts}) -Restore from the variable pointed to by @var{flagp} the setting of the -flags for the exceptions denoted by the value of the parameter -@var{excepts}. -@end deftypefun - -The last function allows to query the current status of the flags. The -flags can be set either explicitely (using @code{fesetexceptflag} or -@code{feclearexcept}) or by a floating-point operation which happened -before. Since the flags are accumulative, the flags must be explicitely -reset using @code{feclearexcept} if one wants to test for a certain -exceptions raised by a specific piece of code. - -@comment fenv.h -@comment ISO -@deftypefun int fetestexcept (int @var{excepts}) -Test whether a subset of the flags indicated by the parameter -@var{except} is currently set. If yes, a nonzero value is returned -which specifies which exceptions are set. Otherwise the result is zero. -@end deftypefun - -@noindent -Code which uses the @code{fetestexcept} function could look like this: - -@smallexample -@{ - double f; - int raised; - feclearexcept (FE_ALL_EXCEPT); - f = compute (); - raised = fetestexcept (FE_OVERFLOW | FE_INVALID); - if (raised & FE_OVERFLOW) @{ /* ... */ @} - if (raised & FE_INVALID) @{ /* ... */ @} - /* ... */ -@} -@end smallexample - -Please note that the return value of @code{fetestexcept} is @code{int} -but this does not mean that the @code{fexcept_t} type is generally -representable as an integer. These are completely independent types. - - -@node FPU environment -@subsection Controlling the Floating-Point environment - -It is sometimes necessary so save the complete status of the -floating-point unit for a certain time to perform some completely -different actions. Beside the status of the exception flags, the -control word for the exceptions and the rounding mode can be saved. - -The file @file{fenv.h} defines the type @code{fenv_t}. The layout of a -variable of this type is implementation defined but the variable is able -to contain the complete status information. To fill a variable of this -type one can use this function: - -@comment fenv.h -@comment ISO -@deftypefun void fegetenv (fenv_t *@var{envp}) -Store the current floating-point environment in the object pointed to by -@var{envp}. -@end deftypefun - -@noindent -Another possibility which is useful in several situations is - -@comment fenv.h -@comment ISO -@deftypefun int feholdexcept (fenv_t *@var{envp}) -Store the current floating-point environment in the object pointed to by -@var{envp}. Afterwards, all exception flags are cleared and if -available a mode is installed which continues on all exceptions and does -not cause a trap to occur. In this case a nonzero value is returned. - -If the floating-point implementation does not support such a non-stop -mode, the return value is zero. -@end deftypefun - -The functions which allow a state of the floating-point unit to be -restored can take two kinds of arguments: - -@itemize @bullet -@item -Pointers to @code{fenv_t} objects which were initialized previously by a -call to @code{fegetenv} or @code{feholdexcept}. -@item -@vindex FE_DFL_ENV -The special macro @code{FE_DFL_ENV} which represents the floating-point -environment as it was available at program start. -@item -Implementation defined macros with names starting with @code{FE_}. - -@vindex FE_NOMASK_ENV -If possible, the GNU C Library defines a macro @code{FE_NOMASK_ENV} -which represents an environment where no exceptions are masked, so every -exception raised causes a trap to occur. You can test for this macro -using @code{#ifdef}. - -Some platforms might define other predefined environments. -@end itemize - -@noindent -To set any of the environments there are two functions defined. - -@deftypefun void fesetenv (const fenv_t *@var{envp}) -Establish the floating-point environment described in the object pointed -to by @var{envp}. Even if one or more exceptions flags in the restored -environment are set no exception is raised. -@end deftypefun - -In some situations the previous status of the exception flags must not -simply be discarded and so this function is useful: - -@deftypefun void feupdateenv (const fenv_t *@var{envp}) -The current status of the floating-point unit is preserved in some -automatic storage before the environment described by the object pointed -to by @var{envp} is installed. Once this is finished all exceptions set -in the original environment which is saved in the automatic storage, is -raised. -@end deftypefun - -This function can be used to execute a part of the program with an -environment which masks all exceptions and before switching back remove -unwanted exception and raise the remaining exceptions. - - -@node Rounding Modes -@subsection Rounding modes of the Floating-Point Unit - -@w{IEEE 754} defines four different rounding modes. If the rounding -mode is supported by the floating-point implementation the corresponding -of the following macros is defined: - -@table @code -@comment fenv.h -@comment ISO -@vindex FE_TONEAREST -@item FE_TONEAREST -Round to nearest. This is the default mode and should always be used -except when a different mode is explicitely required. Only rounding to -nearest guarantees numeric stability of the computations. - -@comment fenv.h -@comment ISO -@vindex FE_UPWARD -@item FE_UPWARD -Round toward @math{+@infinity{}}. - -@comment fenv.h -@comment ISO -@vindex FE_DOWNWARD -@item FE_DOWNWARD -Round toward @math{-@infinity{}}. - -@comment fenv.h -@comment ISO -@vindex FE_TOWARDZERO -@item FE_TOWARDZERO -Round toward zero. -@end table - -At any time one of the above four rounding modes is selected. To get -information about the currently selected mode one can use this function: - -@comment fenv.h -@comment ISO -@deftypefun int fegetround (void) -Return the currently selected rounding mode, represented by one of the -values of the defined rounding mode macros. -@end deftypefun - -@noindent -To set a specific rounding mode the next function can be used. - -@comment fenv.h -@comment ISO -@deftypefun int fesetround (int @var{round}) -Change the currently selected rounding mode to the mode described by the -parameter @var{round}. If @var{round} does not correspond to one of the -supported rounding modes nothing is changed. - -The function returns a nonzero value iff the requested rounding mode can -be established. Otherwise zero is returned. -@end deftypefun - -Changing the rounding mode might be necessary for various reasons. But -changing the mode only to round a given number normally is no good idea. -The standard defines a set of functions which can be used to round an -argument according to some rules and for all of the rounding modes there -is a corresponding function. - -If a large set of number has to be rounded it might be good to change -the rounding mode and to not use the function the library provides. So -the perhaps necessary switching of the rounding mode in the library -function can be avoided. But since not all rounding modes are -guaranteed to exist on any platform this possible implementation cannot -be portably used. A default method has to be implemented as well. - - @node Mathematical Constants @section Predefined Mathematical Constants @cindex constants @cindex mathematical constants -The header @file{math.h} defines a series of mathematical constants if -@code{_BSD_SOURCE} or a more general feature select macro is defined -before including this file. All values are defined as preprocessor -macros starting with @code{M_}. The collection includes: +The header @file{math.h} defines several useful mathematical constants. +All values are defined as preprocessor macros starting with @code{M_}. +The values provided are: @vtable @code @item M_E -The value is that of the base of the natural logarithm. +The base of natural logarithms. @item M_LOG2E -The value is computed as the logarithm to base @code{2} of @code{M_E}. +The logarithm to base @code{2} of @code{M_E}. @item M_LOG10E -The value is computed as the logarithm to base @code{10} of @code{M_E}. +The logarithm to base @code{10} of @code{M_E}. @item M_LN2 -The value is computed as the natural logarithm of @code{2}. +The natural logarithm of @code{2}. @item M_LN10 -The value is computed as the natural logarithm of @code{10}. +The natural logarithm of @code{10}. @item M_PI -The value is those of the number pi. +Pi, the ratio of a circle's circumrefence to its diameter. @item M_PI_2 -The value is those of the number pi divided by two. +Pi divided by two. @item M_PI_4 -The value is those of the number pi divided by four. +Pi divided by four. @item M_1_PI -The value is the reziprocal of the value of the number pi. +The reciprocal of pi (1/pi) @item M_2_PI -The value is two times the reziprocal of the value of the number pi. +Two times the reciprocal of pi. @item M_2_SQRTPI -The value is two times the reziprocal of the square root of the number pi. +Two times the reciprocal of the square root of pi. @item M_SQRT2 -The value is the square root of the value of the number pi. +The square root of two. @item M_SQRT1_2 -The value is the reziprocal of the square root of the value of the number pi. +The reciprocal of the square root of two (also the square root of 1/2). @end vtable -All values are defined as @code{long double} values unless the compiler -does not support this type or @code{__STDC__} is not defined (both is -unlikely). Historically the numbers were @code{double} values and some -old code still relies on this so you might want to add explicit casts if -the extra precision of the @code{long double} value is not needed. One -critical case are functions with a variable number of arguments, such as -@code{printf}. +These constants come from the Unix98 standard and were also available in +4.4BSD; therefore, they are only defined if @code{_BSD_SOURCE} or +@code{_XOPEN_SOURCE=500}, or a more general feature select macro, is +defined. The default set of features includes these constants. +@xref{Feature Test Macros}. + +All values are of type @code{double}. As an extension, the GNU C +library also defines these constants with type @code{long double}. The +@code{long double} macros have a lowercase @samp{l} appended to their +names: @code{M_El}, @code{M_PIl}, and so forth. These are only +available if @code{_GNU_SOURCE} is defined. @vindex PI @emph{Note:} Some programs use a constant named @code{PI} which has the -same value as @code{M_PI}. This probably derives from Stroustroup's -book about his C++ programming language where this value is used in -examples (and perhaps some AT&T headers contain this value). But due to -possible name space problems (@code{PI} is a quite frequently used name) -this value is not added to @file{math.h}. Every program should use -@code{M_PI} instead or add on the compiler command line -@code{-DPI=M_PI}. - - -@node FP Comparison Functions -@section Floating-Point Comparison Functions -@cindex unordered comparison - -The @w{IEEE 754} standards defines a set of functions which allows to -compare even those numbers which normally would cause an exception to be -raised since they are unordered. E.g., the expression - -@smallexample -int v = a < 1.0; -@end smallexample - -@noindent -would raise an exception if @var{a} would be a NaN. Functions to -compare unordered numbers are part of the FORTRAN language for a long -time and the extensions in @w{ISO C 9X} finally introduce them as well -for the C programming language. - -All of the operations are implemented as macros which allow their -arguments to be of either @code{float}, @code{double}, or @code{long -double} type. - -@comment math.h -@comment ISO -@deftypefn {Macro} int isgreater (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) -This macro determines whether the argument @var{x} is greater than -@var{y}. This is equivalent to @code{(@var{x}) > (@var{y})} but no -exception is raised if @var{x} or @var{y} are unordered. -@end deftypefn - -@comment math.h -@comment ISO -@deftypefn {Macro} int isgreaterequal (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) -This macro determines whether the argument @var{x} is greater than or -equal to @var{y}. This is equivalent to @code{(@var{x}) >= (@var{y})} but no -exception is raised if @var{x} or @var{y} are unordered. -@end deftypefn - -@comment math.h -@comment ISO -@deftypefn {Macro} int isless (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) -This macro determines whether the argument @var{x} is less than @var{y}. -This is equivalent @code{(@var{x}) < (@var{y})} but no exception is raised if -@var{x} or @var{y} are unordered. -@end deftypefn - -@comment math.h -@comment ISO -@deftypefn {Macro} int islessequal (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) -This macro determines whether the argument @var{x} is less than or equal -to @var{y}. This is equivalent to @code{(@var{x}) <= (@var{y})} but no -exception is raised if @var{x} or @var{y} are unordered. -@end deftypefn - -@comment math.h -@comment ISO -@deftypefn {Macro} int islessgreater (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) -This macro determines whether the argument @var{x} is less or greater -than @var{y}. This is equivalent to @code{(@var{x}) < (@var{y}) || -(@var{x}) > (@var{y})} (except that @var{x} and @var{y} are only -evaluated once) but no exception is raised if @var{x} or @var{y} are -unordered. -@end deftypefn - -@comment math.h -@comment ISO -@deftypefn {Macro} int isunordered (@emph{real-floating} @var{x}, @emph{real-floating} @var{y}) -This macro determines whether its arguments are unordered. -@end deftypefn - -All the macros are defined in a way to ensure that both arguments are -evaluated exactly once and so they can be used exactly like the builtin -operators. - -On several platform these macros are mapped to efficient instructions -the processor understands. But on machines missing these functions, the -macros above might be rather slow. So it is best to use the builtin -operators unless it is necessary to use unordered comparisons. - -@strong{Note:} There are no macros @code{isequal} or @code{isunequal}. -These macros are not necessary since the @w{IEEE 754} standard requires -that the comparison for equality and unequality do @emph{not} throw an -exception if one of the arguments is an unordered value. - - -@node FP Function Optimizations -@section Is Fast Code or Small Code preferred? -@cindex Optimization - -If an application uses many floating point function it is often the case -that the costs for the function calls itselfs are not neglectable. -Modern processor implementation often can execute the operation itself -very fast but the call means a disturbance of the control flow. - -For this reason the GNU C Library provides optimizations for many of the -frequently used math functions. When the GNU CC is used and the user -activates the optimizer several new inline functions and macros get -defined. These new functions and macros have the same names as the -library function and so get used instead of the later. In case of -inline functions the compiler will decide whether it is reasonable to -use the inline function and this decision is usually correct. - -For the generated code this means that no calls to the library functions -are necessary. This increases the speed significantly. But the -drawback is that the code size increases and this increase is not always -neglectable. - -In cases where the inline functions and macros are not wanted the symbol -@code{__NO_MATH_INLINES} should be defined before any system header is -included. This will make sure only library functions are used. Of -course it can be determined for each single file in the project whether -giving this option is preferred or not. - +same value as @code{M_PI}. This constant is not standard; it may have +appeared in some old AT&T headers, and is mentioned in Stroustrup's book +on C++. It infringes on the user's name space, so the GNU C library +does not define it. Fixing programs written to expect it is simple: +replace @code{PI} with @code{M_PI} throughout, or put @samp{-DPI=M_PI} +on the compiler command line. @node Trig Functions @section Trigonometric Functions @@ -744,10 +134,10 @@ The arguments to all of these functions are in units of radians; recall that pi radians equals 180 degrees. @cindex pi (trigonometric constant) -The math library does define a symbolic constant for pi in @file{math.h} -(@pxref{Mathematical Constants}) when BSD compliance is required -(@pxref{Feature Test Macros}). In case it is not possible to use this -predefined macro one easily can define it: +The math library normally defines @code{M_PI} to a @code{double} +approximation of pi. If strict ISO and/or POSIX compliance +are requested this constant is not defined, but you can easily define it +yourself: @smallexample #define M_PI 3.14159265358979323846264338327 @@ -757,7 +147,6 @@ predefined macro one easily can define it: You can also compute the value of pi with the expression @code{acos (-1.0)}. - @comment math.h @comment ISO @deftypefun double sin (double @var{x}) @@ -784,22 +173,15 @@ radians. The return value is in the range @code{-1} to @code{1}. These functions return the tangent of @var{x}, where @var{x} is given in radians. -The following @code{errno} error conditions are defined for this function: - -@table @code -@item ERANGE Mathematically, the tangent function has singularities at odd multiples of pi/2. If the argument @var{x} is too close to one of these -singularities, @code{tan} sets @code{errno} to @code{ERANGE} and returns -either positive or negative @code{HUGE_VAL}. -@end table +singularities, @code{tan} will signal overflow. @end deftypefun -In many applications where @code{sin} and @code{cos} are used, the value -for the same argument of both of these functions is used at the same -time. Since the algorithm to compute these values is very similar for -both functions there is an additional function which computes both values -at the same time. +In many applications where @code{sin} and @code{cos} are used, the sine +and cosine of the same angle are needed at the same time. It is more +efficient to compute them simultaneously, so the library provides a +function to do that. @comment math.h @comment GNU @@ -811,33 +193,34 @@ cosine of @var{x} in @code{*@var{cos}}, where @var{x} is given in radians. Both values, @code{*@var{sinx}} and @code{*@var{cosx}}, are in the range of @code{-1} to @code{1}. -This function is a GNU extension. It should be used whenever both sine -and cosine are needed but in portable applications there should be a -fallback method for systems without this function. +This function is a GNU extension. Portable programs should be prepared +to cope with its absence. @end deftypefun @cindex complex trigonometric functions -The trigonometric functions are in mathematics not only defined on real -numbers. They can be extended to complex numbers and the @w{ISO C 9X} -standard introduces these variants in the standard math library. +@w{ISO C 9x} defines variants of the trig functions which work on +complex numbers. The GNU C library provides these functions, but they +are only useful if your compiler supports the new complex types defined +by the standard. +@c Change this when gcc is fixed. -zw +(As of this writing GCC supports complex numbers, but there are bugs in +the implementation.) @comment complex.h @comment ISO @deftypefun {complex double} csin (complex double @var{z}) @deftypefunx {complex float} csinf (complex float @var{z}) @deftypefunx {complex long double} csinl (complex long double @var{z}) -These functions return the complex sine of the complex value in @var{z}. +These functions return the complex sine of @var{z}. The mathematical definition of the complex sine is @ifinfo @math{sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i))}. @end ifinfo -@iftex @tex $$\sin(z) = {1\over 2i} (e^{zi} - e^{-zi})$$ @end tex -@end iftex @end deftypefun @comment complex.h @@ -845,17 +228,15 @@ $$\sin(z) = {1\over 2i} (e^{zi} - e^{-zi})$$ @deftypefun {complex double} ccos (complex double @var{z}) @deftypefunx {complex float} ccosf (complex float @var{z}) @deftypefunx {complex long double} ccosl (complex long double @var{z}) -These functions return the complex cosine of the complex value in @var{z}. +These functions return the complex cosine of @var{z}. The mathematical definition of the complex cosine is @ifinfo @math{cos (z) = 1/2 * (exp (z*i) + exp (-z*i))} @end ifinfo -@iftex @tex $$\cos(z) = {1\over 2} (e^{zi} + e^{-zi})$$ @end tex -@end iftex @end deftypefun @comment complex.h @@ -863,17 +244,20 @@ $$\cos(z) = {1\over 2} (e^{zi} + e^{-zi})$$ @deftypefun {complex double} ctan (complex double @var{z}) @deftypefunx {complex float} ctanf (complex float @var{z}) @deftypefunx {complex long double} ctanl (complex long double @var{z}) -These functions return the complex tangent of the complex value in @var{z}. +These functions return the complex tangent of @var{z}. The mathematical definition of the complex tangent is @ifinfo -@math{tan (z) = 1/i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))} +@math{tan (z) = -i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))} @end ifinfo -@iftex @tex -$$\tan(z) = {1\over i} {e^{zi} - e^{-zi}\over e^{zi} + e^{-zi}}$$ +$$\tan(z) = -i \cdot {e^{zi} - e^{-zi}\over e^{zi} + e^{-zi}}$$ @end tex -@end iftex + +@noindent +The complex tangent has poles at @math{pi/2 + 2n}, where @math{n} is an +integer. @code{ctan} may signal overflow if @var{z} is too close to a +pole. @end deftypefun @@ -895,9 +279,9 @@ sine is @var{x}. The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between @code{-pi/2} and @code{pi/2} (inclusive). -@code{asin} fails, and sets @code{errno} to @code{EDOM}, if @var{x} is -out of range. The arc sine function is defined mathematically only -over the domain @code{-1} to @code{1}. +The arc sine function is defined mathematically only +over the domain @code{-1} to @code{1}. If @var{x} is outside the +domain, @code{asin} signals a domain error. @end deftypefun @comment math.h @@ -910,12 +294,11 @@ whose cosine is @var{x}. The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between @code{0} and @code{pi} (inclusive). -@code{acos} fails, and sets @code{errno} to @code{EDOM}, if @var{x} is -out of range. The arc cosine function is defined mathematically only -over the domain @code{-1} to @code{1}. +The arc cosine function is defined mathematically only +over the domain @code{-1} to @code{1}. If @var{x} is outside the +domain, @code{acos} signals a domain error. @end deftypefun - @comment math.h @comment ISO @deftypefun double atan (double @var{x}) @@ -924,8 +307,7 @@ over the domain @code{-1} to @code{1}. These functions compute the arc tangent of @var{x}---that is, the value whose tangent is @var{x}. The value is in units of radians. Mathematically, there are infinitely many such values; the one actually -returned is the one between @code{-pi/2} and @code{pi/2} -(inclusive). +returned is the one between @code{-pi/2} and @code{pi/2} (inclusive). @end deftypefun @comment math.h @@ -933,11 +315,10 @@ returned is the one between @code{-pi/2} and @code{pi/2} @deftypefun double atan2 (double @var{y}, double @var{x}) @deftypefunx float atan2f (float @var{y}, float @var{x}) @deftypefunx {long double} atan2l (long double @var{y}, long double @var{x}) -This is the two argument arc tangent function. It is similar to computing -the arc tangent of @var{y}/@var{x}, except that the signs of both arguments -are used to determine the quadrant of the result, and @var{x} is -permitted to be zero. The return value is given in radians and is in -the range @code{-pi} to @code{pi}, inclusive. +This function computes the arc tangent of @var{y}/@var{x}, but the signs +of both arguments are used to determine the quadrant of the result, and +@var{x} is permitted to be zero. The return value is given in radians +and is in the range @code{-pi} to @code{pi}, inclusive. If @var{x} and @var{y} are coordinates of a point in the plane, @code{atan2} returns the signed angle between the line from the origin @@ -946,15 +327,12 @@ converting Cartesian coordinates to polar coordinates. (To compute the radial coordinate, use @code{hypot}; see @ref{Exponents and Logarithms}.) -The function @code{atan2} sets @code{errno} to @code{EDOM} if both -@var{x} and @var{y} are zero; the return value is not defined in this -case. +@c This is experimentally true. Should it be so? -zw +If both @var{x} and @var{y} are zero, @code{atan2} returns zero. @end deftypefun @cindex inverse complex trigonometric functions - -The inverse trigonometric functions also exist is separate versions -which are usable with complex numbers. +@w{ISO C 9x} defines complex versions of the inverse trig functions. @comment complex.h @comment ISO @@ -962,10 +340,10 @@ which are usable with complex numbers. @deftypefunx {complex float} casinf (complex float @var{z}) @deftypefunx {complex long double} casinl (complex long double @var{z}) These functions compute the complex arc sine of @var{z}---that is, the -value whose sine is @var{z}. The value is in units of radians. +value whose sine is @var{z}. The value returned is in radians. -Unlike the real version of the arc sine function @code{casin} has no -limitation on the argument @var{z}. +Unlike the real-valued functions, @code{casin} is defined for all +values of @var{z}. @end deftypefun @comment complex.h @@ -974,10 +352,10 @@ limitation on the argument @var{z}. @deftypefunx {complex float} cacosf (complex float @var{z}) @deftypefunx {complex long double} cacosl (complex long double @var{z}) These functions compute the complex arc cosine of @var{z}---that is, the -value whose cosine is @var{z}. The value is in units of radians. +value whose cosine is @var{z}. The value returned is in radians. -Unlike the real version of the arc cosine function @code{cacos} has no -limitation on the argument @var{z}. +Unlike the real-valued functions, @code{cacos} is defined for all +values of @var{z}. @end deftypefun @@ -1002,11 +380,11 @@ the value whose tangent is @var{z}. The value is in units of radians. @deftypefun double exp (double @var{x}) @deftypefunx float expf (float @var{x}) @deftypefunx {long double} expl (long double @var{x}) -These functions return the value of @code{e} (the base of natural -logarithms) raised to power @var{x}. +These functions compute @code{e} (the base of natural logarithms) raised +to the power @var{x}. -The function fails, and sets @code{errno} to @code{ERANGE}, if the -magnitude of the result is too large to be representable. +If the magnitude of the result is too large to be representable, +@code{exp} signals overflow. @end deftypefun @comment math.h @@ -1014,11 +392,8 @@ magnitude of the result is too large to be representable. @deftypefun double exp2 (double @var{x}) @deftypefunx float exp2f (float @var{x}) @deftypefunx {long double} exp2l (long double @var{x}) -These functions return the value of @code{2} raised to the power @var{x}. +These functions compute @code{2} raised to the power @var{x}. Mathematically, @code{exp2 (x)} is the same as @code{exp (x * log (2))}. - -The function fails, and sets @code{errno} to @code{ERANGE}, if the -magnitude of the result is too large to be representable. @end deftypefun @comment math.h @@ -1029,15 +404,11 @@ magnitude of the result is too large to be representable. @deftypefunx double pow10 (double @var{x}) @deftypefunx float pow10f (float @var{x}) @deftypefunx {long double} pow10l (long double @var{x}) -These functions return the value of @code{10} raised to the power @var{x}. -Mathematically, @code{exp2 (x)} is the same as @code{exp (x * log (2))}. +These functions compute @code{10} raised to the power @var{x}. +Mathematically, @code{exp10 (x)} is the same as @code{exp (x * log (10))}. -The function fails, and sets @code{errno} to @code{ERANGE}, if the -magnitude of the result is too large to be representable. - -All these functions are GNU extensions. The name @code{pow10} is used -in some old code but the name @code{exp10} clearly is more in the sense -of the ISO library designers and therefore should probably be preferred. +These functions are GNU extensions. The name @code{exp10} is +preferred, since it is analogous to @code{exp} and @code{exp2}. @end deftypefun @@ -1046,20 +417,13 @@ of the ISO library designers and therefore should probably be preferred. @deftypefun double log (double @var{x}) @deftypefunx float logf (float @var{x}) @deftypefunx {long double} logl (long double @var{x}) -These functions return the natural logarithm of @var{x}. @code{exp (log +These functions compute the natural logarithm of @var{x}. @code{exp (log (@var{x}))} equals @var{x}, exactly in mathematics and approximately in C. -The following @code{errno} error conditions are defined for this function: - -@table @code -@item EDOM -The argument @var{x} is negative. The log function is defined -mathematically to return a real result only on positive arguments. - -@item ERANGE -The argument is zero. The log of zero is not defined. -@end table +If @var{x} is negative, @code{log} signals a domain error. If @var{x} +is zero, it returns negative infinity; if @var{x} is too close to zero, +it may signal overflow. @end deftypefun @comment math.h @@ -1067,9 +431,9 @@ The argument is zero. The log of zero is not defined. @deftypefun double log10 (double @var{x}) @deftypefunx float log10f (float @var{x}) @deftypefunx {long double} log10l (long double @var{x}) -These functions return the base-10 logarithm of @var{x}. Except for the -different base, it is similar to the @code{log} function. In fact, +These functions return the base-10 logarithm of @var{x}. @code{log10 (@var{x})} equals @code{log (@var{x}) / log (10)}. + @end deftypefun @comment math.h @@ -1077,8 +441,7 @@ different base, it is similar to the @code{log} function. In fact, @deftypefun double log2 (double @var{x}) @deftypefunx float log2f (float @var{x}) @deftypefunx {long double} log2l (long double @var{x}) -These functions return the base-2 logarithm of @var{x}. Except for the -different base, it is similar to the @code{log} function. In fact, +These functions return the base-2 logarithm of @var{x}. @code{log2 (@var{x})} equals @code{log (@var{x}) / log (2)}. @end deftypefun @@ -1088,12 +451,13 @@ different base, it is similar to the @code{log} function. In fact, @deftypefunx float logbf (float @var{x}) @deftypefunx {long double} logbl (long double @var{x}) These functions extract the exponent of @var{x} and return it as a -signed integer value. If @var{x} is zero, a range error may occur. +floating-point value. If @code{FLT_RADIX} is two, @code{logb} is equal +to @code{floor (log2 (x))}, except it's probably faster. -A special case are subnormal numbers (if supported by the floating-point -format). The exponent returned is not the actual value from @var{x}. -Instead the number is first normalized as if the range of the exponent -field is large enough. +If @var{x} is denormalized, @code{logb} returns the exponent @var{x} +would have if it were normalized. If @var{x} is infinity (positive or +negative), @code{logb} returns @math{@infinity{}}. If @var{x} is zero, +@code{logb} returns @math{@infinity{}}. It does not signal. @end deftypefun @comment math.h @@ -1102,17 +466,34 @@ field is large enough. @deftypefunx int ilogbf (float @var{x}) @deftypefunx int ilogbl (long double @var{x}) These functions are equivalent to the corresponding @code{logb} -functions except that the values are returned as signed integer values. -Since integer values cannot represent infinity and NaN, there are some -special symbols defined to help detect these situations. - -@vindex FP_ILOGB0 -@vindex FP_ILOGBNAN -@code{ilogb} returns @code{FP_ILOGB0} if @var{x} is @code{0} and it -returns @code{FP_ILOGBNAN} if @var{x} is @code{NaN}. These values are -system specific and no fixed value is assigned. More concrete, these -values might even have the same value. So a piece of code handling the -result of @code{ilogb} could look like this: +functions except that they return signed integer values. +@end deftypefun + +@noindent +Since integers cannot represent infinity and NaN, @code{ilogb} instead +returns an integer that can't be the exponent of a normal floating-point +number. @file{math.h} defines constants so you can check for this. + +@comment math.h +@comment ISO +@deftypevr Macro int FP_ILOGB0 +@code{ilogb} returns this value if its argument is @code{0}. The +numeric value is either @code{INT_MIN} or @code{-INT_MAX}. + +This macro is defined in @w{ISO C 9X}. +@end deftypevr + +@comment math.h +@comment ISO +@deftypevr Macro int FP_ILOGBNAN +@code{ilogb} returns this value if its argument is @code{NaN}. The +numeric value is either @code{INT_MIN} or @code{INT_MAX}. + +This macro is defined in @w{ISO C 9X}. +@end deftypevr + +These values are system specific. They might even be the same. The +proper way to test the result of @code{ilogb} is as follows: @smallexample i = ilogb (f); @@ -1134,8 +515,6 @@ if (i == FP_ILOGB0 || i == FP_ILOGBNAN) @} @end smallexample -@end deftypefun - @comment math.h @comment ISO @deftypefun double pow (double @var{base}, double @var{power}) @@ -1144,17 +523,10 @@ if (i == FP_ILOGB0 || i == FP_ILOGBNAN) These are general exponentiation functions, returning @var{base} raised to @var{power}. -@need 250 -The following @code{errno} error conditions are defined for this function: - -@table @code -@item EDOM -The argument @var{base} is negative and @var{power} is not an integral -value. Mathematically, the result would be a complex number in this case. - -@item ERANGE -An underflow or overflow condition was detected in the result. -@end table +Mathematically, @code{pow} would return a complex number when @var{base} +is negative and @var{power} is not an integral value. @code{pow} can't +do that, so instead it signals a domain error. @code{pow} may also +underflow or overflow the destination type. @end deftypefun @cindex square root function @@ -1165,10 +537,8 @@ An underflow or overflow condition was detected in the result. @deftypefunx {long double} sqrtl (long double @var{x}) These functions return the nonnegative square root of @var{x}. -The @code{sqrt} function fails, and sets @code{errno} to @code{EDOM}, if -@var{x} is negative. Mathematically, the square root would be a complex -number. -@c (@pxref{csqrt}) +If @var{x} is negative, @code{sqrt} signals a domain error. +Mathematically, it should return a complex number. @end deftypefun @cindex cube root function @@ -1187,10 +557,10 @@ fail; every representable real value has a representable real cube root. @deftypefunx float hypotf (float @var{x}, float @var{y}) @deftypefunx {long double} hypotl (long double @var{x}, long double @var{y}) These functions return @code{sqrt (@var{x}*@var{x} + -@var{y}*@var{y})}. (This is the length of the hypotenuse of a right +@var{y}*@var{y})}. This is the length of the hypotenuse of a right triangle with sides of length @var{x} and @var{y}, or the distance -of the point (@var{x}, @var{y}) from the origin.) Using this function -instead of the direct formula is highly appreciated since the error is +of the point (@var{x}, @var{y}) from the origin. Using this function +instead of the direct formula is wise, since the error is much smaller. See also the function @code{cabs} in @ref{Absolute Value}. @end deftypefun @@ -1200,7 +570,7 @@ much smaller. See also the function @code{cabs} in @ref{Absolute Value}. @deftypefunx float expm1f (float @var{x}) @deftypefunx {long double} expm1l (long double @var{x}) These functions return a value equivalent to @code{exp (@var{x}) - 1}. -It is computed in a way that is accurate even if the value of @var{x} is +They are computed in a way that is accurate even if @var{x} is near zero---a case where @code{exp (@var{x}) - 1} would be inaccurate due to subtraction of two numbers that are nearly equal. @end deftypefun @@ -1210,39 +580,32 @@ to subtraction of two numbers that are nearly equal. @deftypefun double log1p (double @var{x}) @deftypefunx float log1pf (float @var{x}) @deftypefunx {long double} log1pl (long double @var{x}) -This function returns a value equivalent to @w{@code{log (1 + @var{x})}}. -It is computed in a way that is accurate even if the value of @var{x} is +These functions returns a value equivalent to @w{@code{log (1 + @var{x})}}. +They are computed in a way that is accurate even if @var{x} is near zero. @end deftypefun @cindex complex exponentiation functions @cindex complex logarithm functions -@w{ISO C 9X} defines variants of some of the exponentiation and -logarithm functions. As for the other functions handling complex -numbers these functions are perhaps better optimized and provide better -error checking than a direct use of the formulas of the mathematical -definition. +@w{ISO C 9X} defines complex variants of some of the exponentiation and +logarithm functions. @comment complex.h @comment ISO @deftypefun {complex double} cexp (complex double @var{z}) @deftypefunx {complex float} cexpf (complex float @var{z}) @deftypefunx {complex long double} cexpl (complex long double @var{z}) -These functions return the value of @code{e} (the base of natural -logarithms) raised to power of the complex value @var{z}. - -@noindent +These functions return @code{e} (the base of natural +logarithms) raised to the power of @var{z}. Mathematically this corresponds to the value @ifinfo @math{exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))} @end ifinfo -@iftex @tex -$$\exp(z) = e^z = e^{{\rm Re} z} (\cos ({\rm Im} z) + i \sin ({\rm Im} z))$$ +$$\exp(z) = e^z = e^{{\rm Re}\,z} (\cos ({\rm Im}\,z) + i \sin ({\rm Im}\,z))$$ @end tex -@end iftex @end deftypefun @comment complex.h @@ -1250,21 +613,20 @@ $$\exp(z) = e^z = e^{{\rm Re} z} (\cos ({\rm Im} z) + i \sin ({\rm Im} z))$$ @deftypefun {complex double} clog (complex double @var{z}) @deftypefunx {complex float} clogf (complex float @var{z}) @deftypefunx {complex long double} clogl (complex long double @var{z}) -These functions return the natural logarithm of the complex value -@var{z}. Unlike the real value version @code{log} and its variants, -@code{clog} has no limit for the range of its argument @var{z}. - -@noindent +These functions return the natural logarithm of @var{z}. Mathematically this corresponds to the value @ifinfo @math{log (z) = log (cabs (z)) + I * carg (z)} @end ifinfo -@iftex @tex -$$\log(z) = \log(|z|) + i \arg(z)$$ +$$\log(z) = \log |z| + i \arg z$$ @end tex -@end iftex + +@noindent +@code{clog} has a pole at 0, and will signal overflow if @var{z} equals +or is very close to 0. It is well-defined for all other values of +@var{z}. @end deftypefun @@ -1274,22 +636,16 @@ $$\log(z) = \log(|z|) + i \arg(z)$$ @deftypefunx {complex float} clog10f (complex float @var{z}) @deftypefunx {complex long double} clog10l (complex long double @var{z}) These functions return the base 10 logarithm of the complex value -@var{z}. Unlike the real value version @code{log} and its variants, -@code{clog} has no limit for the range of its argument @var{z}. - -@noindent -Mathematically this corresponds to the value +@var{z}. Mathematically this corresponds to the value @ifinfo @math{log (z) = log10 (cabs (z)) + I * carg (z)} @end ifinfo -@iftex @tex -$$\log_{10}(z) = \log_{10}(|z|) + i \arg(z)$$ +$$\log_{10}(z) = \log_{10}|z| + i \arg z$$ @end tex -@end iftex -This function is a GNU extension. +These functions are GNU extensions. @end deftypefun @comment complex.h @@ -1297,9 +653,8 @@ This function is a GNU extension. @deftypefun {complex double} csqrt (complex double @var{z}) @deftypefunx {complex float} csqrtf (complex float @var{z}) @deftypefunx {complex long double} csqrtl (complex long double @var{z}) -These functions return the complex root of the argument @var{z}. Unlike -the @code{sqrt} function these functions do not have any restriction on -the value of the argument. +These functions return the complex square root of the argument @var{z}. Unlike +the real-valued functions, they are defined for all values of @var{z}. @end deftypefun @comment complex.h @@ -1307,20 +662,10 @@ the value of the argument. @deftypefun {complex double} cpow (complex double @var{base}, complex double @var{power}) @deftypefunx {complex float} cpowf (complex float @var{base}, complex float @var{power}) @deftypefunx {complex long double} cpowl (complex long double @var{base}, complex long double @var{power}) -These functions return the complex value @var{base} raised to the power of -@var{power}. This is computed as - -@ifinfo -@math{cpow (x, y) = cexp (y * clog (x))} -@end ifinfo -@iftex -@tex -$${\rm cpow}(x, y) = e^{y \log(x)}$$ -@end tex -@end iftex +These functions return @var{base} raised to the power of +@var{power}. This is equivalent to @w{@code{cexp (y * clog (x))}} @end deftypefun - @node Hyperbolic Functions @section Hyperbolic Functions @cindex hyperbolic functions @@ -1334,9 +679,8 @@ see @ref{Exponents and Logarithms}. @deftypefunx float sinhf (float @var{x}) @deftypefunx {long double} sinhl (long double @var{x}) These functions return the hyperbolic sine of @var{x}, defined -mathematically as @w{@code{(exp (@var{x}) - exp (-@var{x})) / 2}}. The -function fails, and sets @code{errno} to @code{ERANGE}, if the value of -@var{x} is too large; that is, if overflow occurs. +mathematically as @w{@code{(exp (@var{x}) - exp (-@var{x})) / 2}}. They +may signal overflow if @var{x} is too large. @end deftypefun @comment math.h @@ -1346,8 +690,7 @@ function fails, and sets @code{errno} to @code{ERANGE}, if the value of @deftypefunx {long double} coshl (long double @var{x}) These function return the hyperbolic cosine of @var{x}, defined mathematically as @w{@code{(exp (@var{x}) + exp (-@var{x})) / 2}}. -The function fails, and sets @code{errno} to @code{ERANGE}, if the value -of @var{x} is too large; that is, if overflow occurs. +They may signal overflow if @var{x} is too large. @end deftypefun @comment math.h @@ -1355,16 +698,15 @@ of @var{x} is too large; that is, if overflow occurs. @deftypefun double tanh (double @var{x}) @deftypefunx float tanhf (float @var{x}) @deftypefunx {long double} tanhl (long double @var{x}) -These functions return the hyperbolic tangent of @var{x}, whose -mathematical definition is @w{@code{sinh (@var{x}) / cosh (@var{x})}}. +These functions return the hyperbolic tangent of @var{x}, +defined mathematically as @w{@code{sinh (@var{x}) / cosh (@var{x})}}. +They may signal overflow if @var{x} is too large. @end deftypefun @cindex hyperbolic functions -There are counterparts for these hyperbolic functions which work with -complex valued arguments. They should always be used instead of the -obvious mathematical formula since the implementations in the math -library are optimized for accuracy and speed. +There are counterparts for the hyperbolic functions which take +complex arguments. @comment complex.h @comment ISO @@ -1372,9 +714,7 @@ library are optimized for accuracy and speed. @deftypefunx {complex float} csinhf (complex float @var{z}) @deftypefunx {complex long double} csinhl (complex long double @var{z}) These functions return the complex hyperbolic sine of @var{z}, defined -mathematically as @w{@code{(exp (@var{z}) - exp (-@var{z})) / 2}}. The -function fails, and sets @code{errno} to @code{ERANGE}, if the value of -result is too large. +mathematically as @w{@code{(exp (@var{z}) - exp (-@var{z})) / 2}}. @end deftypefun @comment complex.h @@ -1383,9 +723,7 @@ result is too large. @deftypefunx {complex float} ccoshf (complex float @var{z}) @deftypefunx {complex long double} ccoshl (complex long double @var{z}) These functions return the complex hyperbolic cosine of @var{z}, defined -mathematically as @w{@code{(exp (@var{z}) + exp (-@var{z})) / 2}}. The -function fails, and sets @code{errno} to @code{ERANGE}, if the value of -result is too large. +mathematically as @w{@code{(exp (@var{z}) + exp (-@var{z})) / 2}}. @end deftypefun @comment complex.h @@ -1393,8 +731,8 @@ result is too large. @deftypefun {complex double} ctanh (complex double @var{z}) @deftypefunx {complex float} ctanhf (complex float @var{z}) @deftypefunx {complex long double} ctanhl (complex long double @var{z}) -These functions return the complex hyperbolic tangent of @var{z}, whose -mathematical definition is @w{@code{csinh (@var{z}) / ccosh (@var{z})}}. +These functions return the complex hyperbolic tangent of @var{z}, +defined mathematically as @w{@code{csinh (@var{z}) / ccosh (@var{z})}}. @end deftypefun @@ -1416,7 +754,7 @@ value whose hyperbolic sine is @var{x}. @deftypefunx {long double} acoshl (long double @var{x}) These functions return the inverse hyperbolic cosine of @var{x}---the value whose hyperbolic cosine is @var{x}. If @var{x} is less than -@code{1}, @code{acosh} returns @code{HUGE_VAL}. +@code{1}, @code{acosh} signals a domain error. @end deftypefun @comment math.h @@ -1426,8 +764,8 @@ value whose hyperbolic cosine is @var{x}. If @var{x} is less than @deftypefunx {long double} atanhl (long double @var{x}) These functions return the inverse hyperbolic tangent of @var{x}---the value whose hyperbolic tangent is @var{x}. If the absolute value of -@var{x} is greater than or equal to @code{1}, @code{atanh} returns -@code{HUGE_VAL}. +@var{x} is greater than @code{1}, @code{atanh} signals a domain error; +if it is equal to 1, @code{atanh} returns infinity. @end deftypefun @cindex inverse complex hyperbolic functions @@ -1448,8 +786,7 @@ These functions return the inverse complex hyperbolic sine of @deftypefunx {complex long double} cacoshl (complex long double @var{z}) These functions return the inverse complex hyperbolic cosine of @var{z}---the value whose complex hyperbolic cosine is @var{z}. Unlike -the real valued function @code{acosh} there is not limit for the range -of the argument. +the real-valued functions, there are no restrictions on the value of @var{z}. @end deftypefun @comment complex.h @@ -1459,10 +796,157 @@ of the argument. @deftypefunx {complex long double} catanhl (complex long double @var{z}) These functions return the inverse complex hyperbolic tangent of @var{z}---the value whose complex hyperbolic tangent is @var{z}. Unlike -the real valued function @code{atanh} there is not limit for the range -of the argument. +the real-valued functions, there are no restrictions on the value of +@var{z}. @end deftypefun +@node Special Functions +@section Special Functions +@cindex special functions +@cindex Bessel functions +@cindex gamma function + +These are some more exotic mathematical functions, which are sometimes +useful. Currently they only have real-valued versions. + +@comment math.h +@comment SVID +@deftypefun double erf (double @var{x}) +@deftypefunx float erff (float @var{x}) +@deftypefunx {long double} erfl (long double @var{x}) +@code{erf} returns the error function of @var{x}. The error +function is defined as +@tex +$$\hbox{erf}(x) = {2\over\sqrt{\pi}}\cdot\int_0^x e^{-t^2} \hbox{d}t$$ +@end tex +@ifnottex +@smallexample +erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt +@end smallexample +@end ifnottex +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double erfc (double @var{x}) +@deftypefunx float erfcf (float @var{x}) +@deftypefunx {long double} erfcl (long double @var{x}) +@code{erfc} returns @code{1.0 - erf(@var{x})}, but computed in a +fashion that avoids round-off error when @var{x} is large. +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double lgamma (double @var{x}) +@deftypefunx float lgammaf (float @var{x}) +@deftypefunx {long double} lgammal (long double @var{x}) +@code{lgamma} returns the natural logarithm of the absolute value of +the gamma function of @var{x}. The gamma function is defined as +@tex +$$\Gamma(x) = \int_0^\infty t^{x-1} e^{-t} \hbox{d}t$$ +@end tex +@ifnottex +@smallexample +gamma (x) = integral from 0 to @infinity{} of t^(x-1) e^-t dt +@end smallexample +@end ifnottex + +@vindex signgam +The sign of the gamma function is stored in the global variable +@var{signgam}, which is declared in @file{math.h}. It is @code{1} if +the intermediate result was positive or zero, and, @code{-1} if it was +negative. + +You can compute the actual gamma function as follows: +@smallexample +lgam = lgamma(x); +gam = signgam*exp(lgam); +@end smallexample + +The gamma function has singularities at the nonpositive integers. +@code{lgamma} will raise the zero divide exception if evaluated at a +singularity. +@end deftypefun + +@comment math.h +@comment XPG +@deftypefun double lgamma_r (double @var{x}) +@deftypefunx float lgammaf_r (float @var{x}) +@deftypefunx {long double} lgammal_r (long double @var{x}) +@code{lgamma_r} is just like @code{lgamma}, but it stores the sign of +the intermediate result in the variable pointed to by @var{signp} +instead of in the @var{signgam} global. +@end deftypefun + +@ignore +@comment math.h +@comment SVID +@deftypefun double gamma (double @var{x}) +@deftypefunx float gammaf (float @var{x}) +@deftypefunx {long double} gammal (long double @var{x}) +??? _not_ exp(lgamma())*signgam - historical? +@end deftypefun +@end ignore + +@comment math.h +@comment SVID +@deftypefun double j0 (double @var{x}) +@deftypefunx float j0f (float @var{x}) +@deftypefunx {long double} j0l (long double @var{x}) +@code{j0} returns the Bessel function of the first kind of order 0 of +@var{x}. It may signal underflow if @var{x} is too large. +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double j1 (double @var{x}) +@deftypefunx float j1f (float @var{x}) +@deftypefunx {long double} j1l (long double @var{x}) +@code{j1} returns the Bessel function of the first kind of order 1 of +@var{x}. It may signal underflow if @var{x} is too large. +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double jn (int n, double @var{x}) +@deftypefunx float jnf (int n, float @var{x}) +@deftypefunx {long double} jnl (int n, long double @var{x}) +@code{jn} returns the Bessel function of the first kind of order +@var{n} of @var{x}. It may signal underflow if @var{x} is too large. +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double y0 (double @var{x}) +@deftypefunx float y0f (float @var{x}) +@deftypefunx {long double} y0l (long double @var{x}) +@code{y0} returns the Bessel function of the second kind of order 0 of +@var{x}. It may signal underflow if @var{x} is too large. If @var{x} +is negative, @code{y0} signals a domain error; if it is zero, +@code{y0} signals overflow and returns @math{-@infinity}. +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double y1 (double @var{x}) +@deftypefunx float y1f (float @var{x}) +@deftypefunx {long double} y1l (long double @var{x}) +@code{y1} returns the Bessel function of the second kind of order 1 of +@var{x}. It may signal underflow if @var{x} is too large. If @var{x} +is negative, @code{y1} signals a domain error; if it is zero, +@code{y1} signals overflow and returns @math{-@infinity}. +@end deftypefun + +@comment math.h +@comment SVID +@deftypefun double yn (int n, double @var{x}) +@deftypefunx float ynf (int n, float @var{x}) +@deftypefunx {long double} ynl (int n, long double @var{x}) +@code{yn} returns the Bessel function of the second kind of order @var{n} of +@var{x}. It may signal underflow if @var{x} is too large. If @var{x} +is negative, @code{yn} signals a domain error; if it is zero, +@code{yn} signals overflow and returns @math{-@infinity}. +@end deftypefun @node Pseudo-Random Numbers @section Pseudo-Random Numbers @@ -1472,19 +956,19 @@ of the argument. This section describes the GNU facilities for generating a series of pseudo-random numbers. The numbers generated are not truly random; -typically, they form a sequence that repeats periodically, with a -period so large that you can ignore it for ordinary purposes. The -random number generator works by remembering at all times a @dfn{seed} -value which it uses to compute the next random number and also to -compute a new seed. +typically, they form a sequence that repeats periodically, with a period +so large that you can ignore it for ordinary purposes. The random +number generator works by remembering a @dfn{seed} value which it uses +to compute the next random number and also to compute a new seed. Although the generated numbers look unpredictable within one run of a program, the sequence of numbers is @emph{exactly the same} from one run to the next. This is because the initial seed is always the same. This is convenient when you are debugging a program, but it is unhelpful if -you want the program to behave unpredictably. If you want truly random -numbers, not just pseudo-random, specify a seed based on the current -time. +you want the program to behave unpredictably. If you want a different +pseudo-random series each time your program runs, you must specify a +different seed each time. For ordinary purposes, basing the seed on the +current time works well. You can get repeatable sequences of numbers on a particular machine type by specifying the same initial seed value for the random number @@ -1493,19 +977,20 @@ the same seed, used in different C libraries or on different CPU types, will give you different random numbers. The GNU library supports the standard @w{ISO C} random number functions -plus two other sets derived from BSD and SVID. We recommend you use the -standard ones, @code{rand} and @code{srand} if only a small number of -random bits are required. The SVID functions provide an interface which -allows better random number generator algorithms and they return up to -48 random bits in one calls and they also return random floating-point -numbers if wanted. The SVID function might not be available on some BSD -derived systems but since they are required in the XPG they are -available on all Unix-conformant systems. +plus two other sets derived from BSD and SVID. The BSD and @w{ISO C} +functions provide identical, somewhat limited functionality. If only a +small number of random bits are required, we recommend you use the +@w{ISO C} interface, @code{rand} and @code{srand}. The SVID functions +provide a more flexible interface, which allows better random number +generator algorithms, provides more random bits (up to 48) per call, and +can provide random floating-point numbers. These functions are required +by the XPG standard and therefore will be present in all modern Unix +systems. @menu -* ISO Random:: @code{rand} and friends. -* BSD Random:: @code{random} and friends. -* SVID Random:: @code{drand48} and friends. +* ISO Random:: @code{rand} and friends. +* BSD Random:: @code{random} and friends. +* SVID Random:: @code{drand48} and friends. @end menu @node ISO Random @@ -1521,18 +1006,17 @@ To use these facilities, you should include the header file @comment stdlib.h @comment ISO @deftypevr Macro int RAND_MAX -The value of this macro is an integer constant expression that -represents the maximum possible value returned by the @code{rand} -function. In the GNU library, it is @code{037777777}, which is the -largest signed integer representable in 32 bits. In other libraries, it -may be as low as @code{32767}. +The value of this macro is an integer constant representing the largest +value the @code{rand} function can return. In the GNU library, it is +@code{2147483647}, which is the largest signed integer representable in +32 bits. In other libraries, it may be as low as @code{32767}. @end deftypevr @comment stdlib.h @comment ISO @deftypefun int rand (void) The @code{rand} function returns the next pseudo-random number in the -series. The value is in the range from @code{0} to @code{RAND_MAX}. +series. The value ranges from @code{0} to @code{RAND_MAX}. @end deftypefun @comment stdlib.h @@ -1543,31 +1027,27 @@ pseudo-random numbers. If you call @code{rand} before a seed has been established with @code{srand}, it uses the value @code{1} as a default seed. -To produce truly random numbers (not just pseudo-random), do @code{srand -(time (0))}. +To produce a different pseudo-random series each time your program is +run, do @code{srand (time (0))}. @end deftypefun -A completely broken interface was designed by the POSIX.1 committee to -support reproducible random numbers in multi-threaded programs. +POSIX.1 extended the C standard functions to support reproducible random +numbers in multi-threaded programs. However, the extension is badly +designed and unsuitable for serious work. @comment stdlib.h @comment POSIX.1 @deftypefun int rand_r (unsigned int *@var{seed}) This function returns a random number in the range 0 to @code{RAND_MAX} -just as @code{rand} does. But this function does not keep an internal -state for the RNG. Instead the @code{unsigned int} variable pointed to -by the argument @var{seed} is the only state. Before the value is -returned the state will be updated so that the next call will return a -new number. - -I.e., the state of the RNG can only have as much bits as the type -@code{unsigned int} has. This is far too few to provide a good RNG. -This interface is broken by design. +just as @code{rand} does. However, all its state is stored in the +@var{seed} argument. This means the RNG's state can only have as many +bits as the type @code{unsigned int} has. This is far too few to +provide a good RNG. -If the program requires reproducible random numbers in multi-threaded -programs the reentrant SVID functions are probably a better choice. But -these functions are GNU extensions and therefore @code{rand_r}, as being -standardized in POSIX.1, should always be kept as a default method. +If your program requires a reentrant RNG, we recommend you use the +reentrant GNU extensions to the SVID random number generator. The +POSIX.1 interface should only be used when the GNU extensions are not +available. @end deftypefun @@ -1585,24 +1065,24 @@ The prototypes for these functions are in @file{stdlib.h}. @comment BSD @deftypefun {int32_t} random (void) This function returns the next pseudo-random number in the sequence. -The range of values returned is from @code{0} to @code{RAND_MAX}. +The value returned ranges from @code{0} to @code{RAND_MAX}. -@strong{Please note:} Historically this function returned a @code{long -int} value. But with the appearance of 64bit machines this could lead -to severe compatibility problems and therefore the type now explicitly -limits the return value to 32bit. +@strong{Note:} Historically this function returned a @code{long +int} value. On 64bit systems @code{long int} would have been larger +than programs expected, so @code{random} is now defined to return +exactly 32 bits. @end deftypefun @comment stdlib.h @comment BSD @deftypefun void srandom (unsigned int @var{seed}) -The @code{srandom} function sets the seed for the current random number -state based on the integer @var{seed}. If you supply a @var{seed} value +The @code{srandom} function sets the state of the random number +generator based on the integer @var{seed}. If you supply a @var{seed} value of @code{1}, this will cause @code{random} to reproduce the default set of random numbers. -To produce truly random numbers (not just pseudo-random), do -@code{srandom (time (0))}. +To produce a different set of pseudo-random numbers each time your +program runs, do @code{srandom (time (0))}. @end deftypefun @comment stdlib.h @@ -1610,9 +1090,9 @@ To produce truly random numbers (not just pseudo-random), do @deftypefun {void *} initstate (unsigned int @var{seed}, void *@var{state}, size_t @var{size}) The @code{initstate} function is used to initialize the random number generator state. The argument @var{state} is an array of @var{size} -bytes, used to hold the state information. The size must be at least 8 -bytes, and optimal sizes are 8, 16, 32, 64, 128, and 256. The bigger -the @var{state} array, the better. +bytes, used to hold the state information. It is initialized based on +@var{seed}. The size must be between 8 and 256 bytes, and should be a +power of two. The bigger the @var{state} array, the better. The return value is the previous value of the state information array. You can use this value later as an argument to @code{setstate} to @@ -1631,13 +1111,12 @@ You can use this value later as an argument to @code{setstate} to restore that state. @end deftypefun - @node SVID Random @subsection SVID Random Number Function The C library on SVID systems contains yet another kind of random number generator functions. They use a state of 48 bits of data. The user can -choose among a collection of functions which all return the random bits +choose among a collection of functions which return the random bits in different forms. Generally there are two kinds of functions: those which use a state of @@ -1973,3 +1452,37 @@ If the return value is non-negative the function call succeeded. This function is a GNU extension and should not be used in portable programs. @end deftypefun + +@node FP Function Optimizations +@section Is Fast Code or Small Code preferred? +@cindex Optimization + +If an application uses many floating point function it is often the case +that the costs for the function calls itselfs are not neglectable. +Modern processor implementation often can execute the operation itself +very fast but the call means a disturbance of the control flow. + +For this reason the GNU C Library provides optimizations for many of the +frequently used math functions. When the GNU CC is used and the user +activates the optimizer several new inline functions and macros get +defined. These new functions and macros have the same names as the +library function and so get used instead of the later. In case of +inline functions the compiler will decide whether it is reasonable to +use the inline function and this decision is usually correct. + +For the generated code this means that no calls to the library functions +are necessary. This increases the speed significantly. But the +drawback is that the code size increases and this increase is not always +neglectable. + +In cases where the inline functions and macros are not wanted the symbol +@code{__NO_MATH_INLINES} should be defined before any system header is +included. This will make sure only library functions are used. Of +course it can be determined for each single file in the project whether +giving this option is preferred or not. + +Not all hardware implements the entire @w{IEEE 754} standard, or if it +does, there may be a substantial performance penalty for using some of +its features. For example, enabling traps on some processors forces +the FPU to run unpipelined, which more than doubles calculation time. +@c ***Add explanation of -lieee, -mieee. diff --git a/manual/mbyte.texi b/manual/mbyte.texi index 4ff9a1b..8f3c192 100644 --- a/manual/mbyte.texi +++ b/manual/mbyte.texi @@ -1,4 +1,5 @@ @node Extended Characters, Locales, String and Array Utilities, Top +@c %MENU% Support for extended character sets @chapter Extended Characters A number of languages use character sets that are larger than the range diff --git a/manual/memory.texi b/manual/memory.texi index 49c2fda..b87bc3f 100644 --- a/manual/memory.texi +++ b/manual/memory.texi @@ -3,6 +3,7 @@ @node Memory Allocation, Character Handling, Error Reporting, Top @chapter Memory Allocation +@c %MENU% Allocating memory dynamically and manipulating it via pointers @cindex memory allocation @cindex storage allocation diff --git a/manual/message.texi b/manual/message.texi index fb61262..c0ab281 100644 --- a/manual/message.texi +++ b/manual/message.texi @@ -1,4 +1,5 @@ -@node Message Translation +@node Message Translation, Searching and Sorting, Locales, Top +@c %MENU% How to make the program speak the user's language @chapter Message Translation The program's interface with the human should be designed in a way to diff --git a/manual/nss.texi b/manual/nss.texi index a5dd635..f6293c0 100644 --- a/manual/nss.texi +++ b/manual/nss.texi @@ -1,11 +1,10 @@ -@c each section should have index entries corresponding to the section title - -@node Name Service Switch +@node Name Service Switch, Users and Groups, Job Control, Top @chapter System Databases and Name Service Switch - +@c %MENU% Accessing system databases @cindex Name Service Switch @cindex NSS @cindex databases + Various functions in the C Library need to be configured to work correctly in the local environment. Traditionally, this was done by using files (e.g., @file{/etc/passwd}), but other nameservices (like the diff --git a/manual/pattern.texi b/manual/pattern.texi index 90529ba..24e8e4c 100644 --- a/manual/pattern.texi +++ b/manual/pattern.texi @@ -1,4 +1,5 @@ @node Pattern Matching, I/O Overview, Searching and Sorting, Top +@c %MENU% Matching shell ``globs'' and regular expressions @chapter Pattern Matching The GNU C Library provides pattern matching facilities for two kinds of diff --git a/manual/pipe.texi b/manual/pipe.texi index 274b93d..9050ec8 100644 --- a/manual/pipe.texi +++ b/manual/pipe.texi @@ -1,4 +1,5 @@ @node Pipes and FIFOs, Sockets, File System Interface, Top +@c %MENU% A simple interprocess communication mechanism @chapter Pipes and FIFOs @cindex pipe diff --git a/manual/process.texi b/manual/process.texi index e105342..46aeff6 100644 --- a/manual/process.texi +++ b/manual/process.texi @@ -1,4 +1,5 @@ -@node Processes +@node Processes, Job Control, Process Startup, Top +@c %MENU% How to create processes and run other programs @chapter Processes @cindex process diff --git a/manual/search.texi b/manual/search.texi index 013c584..ae6d5ef 100644 --- a/manual/search.texi +++ b/manual/search.texi @@ -1,4 +1,5 @@ @node Searching and Sorting, Pattern Matching, Message Translation, Top +@c %MENU% General searching and sorting functions @chapter Searching and Sorting This chapter describes functions for searching and sorting arrays of diff --git a/manual/setjmp.texi b/manual/setjmp.texi index b8e7a45..6e3408c 100644 --- a/manual/setjmp.texi +++ b/manual/setjmp.texi @@ -1,4 +1,5 @@ @node Non-Local Exits, Signal Handling, Date and Time, Top +@c %MENU% Jumping out of nested function calls @chapter Non-Local Exits @cindex non-local exits @cindex long jumps diff --git a/manual/signal.texi b/manual/signal.texi index fc05d22..029485c 100644 --- a/manual/signal.texi +++ b/manual/signal.texi @@ -1,4 +1,5 @@ @node Signal Handling, Process Startup, Non-Local Exits, Top +@c %MENU% How to send, block, and handle signals @chapter Signal Handling @cindex signal diff --git a/manual/socket.texi b/manual/socket.texi index 8ac5fa5..4de5b9c 100644 --- a/manual/socket.texi +++ b/manual/socket.texi @@ -1,4 +1,5 @@ @node Sockets, Low-Level Terminal Interface, Pipes and FIFOs, Top +@c %MENU% A more complicated IPC mechanism, with networking support @chapter Sockets This chapter describes the GNU facilities for interprocess diff --git a/manual/startup.texi b/manual/startup.texi index 2a55e39..dd21c89 100644 --- a/manual/startup.texi +++ b/manual/startup.texi @@ -1,4 +1,5 @@ -@node Process Startup +@node Process Startup, Processes, Signal Handling, Top +@c %MENU% Writing the beginning and end of your program @chapter Process Startup and Termination @cindex process diff --git a/manual/stdio.texi b/manual/stdio.texi index 4d054c0..c930471 100644 --- a/manual/stdio.texi +++ b/manual/stdio.texi @@ -1,4 +1,5 @@ @node I/O on Streams, Low-Level I/O, I/O Overview, Top +@c %MENU% Hign-level, portable I/O facilities @chapter Input/Output on Streams @c fix an overfull: @tex diff --git a/manual/string.texi b/manual/string.texi index dd3c68d..2bbc238 100644 --- a/manual/string.texi +++ b/manual/string.texi @@ -1,4 +1,5 @@ @node String and Array Utilities, Extended Characters, Character Handling, Top +@c %MENU% Utilities for copying and comparing strings and arrays @chapter String and Array Utilities Operations on strings (or arrays of characters) are an important part of diff --git a/manual/sysinfo.texi b/manual/sysinfo.texi index f35aa8b..5f599c4 100644 --- a/manual/sysinfo.texi +++ b/manual/sysinfo.texi @@ -1,4 +1,5 @@ @node System Information, System Configuration, Users and Groups, Top +@c %MENU% Getting information about the hardware and operating system @chapter System Information This chapter describes functions that return information about the diff --git a/manual/terminal.texi b/manual/terminal.texi index 217cfc5..85600b0 100644 --- a/manual/terminal.texi +++ b/manual/terminal.texi @@ -1,4 +1,5 @@ -@node Low-Level Terminal Interface +@node Low-Level Terminal Interface, Mathematics, Sockets, Top +@c %MENU% How to change the characteristics of a terminal device @chapter Low-Level Terminal Interface This chapter describes functions that are specific to terminal devices. diff --git a/manual/texis b/manual/texis new file mode 100644 index 0000000..4459561 --- /dev/null +++ b/manual/texis @@ -0,0 +1,78 @@ +texis = \ +intro.texi \ +creature.texi \ +errno.texi \ +memory.texi \ +ctype.texi \ +string.texi \ +stpcpy.c.texi \ +strdupa.c.texi \ +strncat.c.texi \ +mbyte.texi \ +locale.texi \ +message.texi \ +search.texi \ +search.c.texi \ +pattern.texi \ +io.texi \ +stdio.texi \ +rprintf.c.texi \ +memopen.c.texi \ +memstrm.c.texi \ +fmtmsgexpl.c.texi \ +llio.texi \ +select.c.texi \ +filesys.texi \ +dir.c.texi \ +dir2.c.texi \ +pipe.texi \ +pipe.c.texi \ +popen.c.texi \ +socket.texi \ +mkfsock.c.texi \ +mkisock.c.texi \ +isockad.c.texi \ +inetcli.c.texi \ +inetsrv.c.texi \ +filesrv.c.texi \ +filecli.c.texi \ +terminal.texi \ +termios.c.texi \ +math.texi \ +arith.texi \ +time.texi \ +strftim.c.texi \ +setjmp.texi \ +setjmp.c.texi \ +signal.texi \ +sigh1.c.texi \ +sigusr.c.texi \ +startup.texi \ +getopt.texi \ +testopt.c.texi \ +longopt.c.texi \ +argp.texi \ +argp-ex1.c.texi \ +argp-ex2.c.texi \ +argp-ex3.c.texi \ +argp-ex4.c.texi \ +subopt.c.texi \ +atexit.c.texi \ +process.texi \ +job.texi \ +nss.texi \ +nsswitch.texi \ +users.texi \ +db.c.texi \ +sysinfo.texi \ +conf.texi \ +../linuxthreads/linuxthreads.texi \ +lang.texi \ +add.c.texi \ +header.texi \ +summary.texi \ +install.texi \ +maint.texi \ +contrib.texi \ +lgpl.texinfo \ + diff --git a/manual/texis.awk b/manual/texis.awk new file mode 100644 index 0000000..a2a8dbf --- /dev/null +++ b/manual/texis.awk @@ -0,0 +1,21 @@ +BEGIN { + print "texis = \\"; + for(x = 1; x < ARGC; x++) + { + input[0] = ARGV[x]; + print ARGV[x], "\\"; + for (s = 0; s >= 0; s--) + { + while ((getline < input[s]) > 0) + { + if ($1 == "@include") + { + input[++s] = $2; + print $2, "\\"; + } + } + close(input[stackptr]); + } + } + print ""; +} diff --git a/manual/time.texi b/manual/time.texi index 540bca1..09c3a9f 100644 --- a/manual/time.texi +++ b/manual/time.texi @@ -1,4 +1,5 @@ @node Date and Time, Non-Local Exits, Arithmetic, Top +@c %MENU% Functions for getting the date and time and formatting them nicely @chapter Date and Time This chapter describes functions for manipulating dates and times, diff --git a/manual/top-menu.texi b/manual/top-menu.texi new file mode 100644 index 0000000..2ad64ae --- /dev/null +++ b/manual/top-menu.texi @@ -0,0 +1,499 @@ +@menu +* Introduction:: Purpose of the GNU C Library. +* Error Reporting:: How library functions report errors. +* Memory Allocation:: Allocating memory dynamically and + manipulating it via pointers. +* Character Handling:: Character testing and conversion functions. +* String and Array Utilities:: Utilities for copying and comparing strings + and arrays. +* Extended Characters:: Support for extended character sets. +* Locales:: The country and language can affect the + behavior of library functions. +* Message Translation:: How to make the program speak the user's + language. +* Searching and Sorting:: General searching and sorting functions. +* Pattern Matching:: Matching shell ``globs'' and regular + expressions. +* I/O Overview:: Introduction to the I/O facilities. +* I/O on Streams:: Hign-level, portable I/O facilities. +* Low-Level I/O:: Low-level, less portable I/O. +* File System Interface:: Functions for manipulating files. +* Pipes and FIFOs:: A simple interprocess communication + mechanism. +* Sockets:: A more complicated IPC mechanism, with + networking support. +* Low-Level Terminal Interface:: How to change the characteristics of a + terminal device. +* Mathematics:: Math functions, useful constants, random + numbers. +* Arithmetic:: Low level arithmetic functions. +* Date and Time:: Functions for getting the date and time and + formatting them nicely. +* Non-Local Exits:: Jumping out of nested function calls. +* Signal Handling:: How to send, block, and handle signals. +* Process Startup:: Writing the beginning and end of your + program. +* Processes:: How to create processes and run other + programs. +* Job Control:: All about process groups and sessions. +* Name Service Switch:: Accessing system databases. +* Users and Groups:: How users are identified and classified. +* System Information:: Getting information about the hardware and + operating system. +* System Configuration:: Parameters describing operating system + limits. + +Add-ons + +* POSIX Threads:: The standard threads library. + +Appendices + +* Language Features:: C language features provided by the library. +* Library Summary:: A summary showing the syntax, header file, + and derivation of each library feature. +* Installation:: How to install the GNU C library. +* Maintenance:: How to enhance and port the GNU C Library. +* Contributors:: Who wrote what parts of the GNU C library. +* Copying:: The GNU Library General Public License says + how you can copy and share the GNU C Library. + +Indices + +* Concept Index:: Index of concepts and names. +* Type Index:: Index of types and type qualifiers. +* Function Index:: Index of functions and function-like macros. +* Variable Index:: Index of variables and variable-like macros. +* File Index:: Index of programs and files. + + --- The Detailed Node Listing --- + +Introduction + +* Getting Started:: What this manual is for and how to use it. +* Standards and Portability:: Standards and sources upon which the GNU + C library is based. +* Using the Library:: Some practical uses for the library. +* Roadmap to the Manual:: Overview of the remaining chapters in + this manual. + +Error Reporting + +* Checking for Errors:: How errors are reported by library functions. +* Error Codes:: Error code macros; all of these expand + into integer constant values. +* Error Messages:: Mapping error codes onto error messages. + +Memory Allocation + +* Memory Concepts:: An introduction to concepts and terminology. +* Dynamic 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. +* Obstacks:: Obstacks are less general than malloc + but more efficient and convenient. +* Variable Size Automatic:: Allocation of variable-sized blocks + of automatic storage that are freed when the + calling function returns. +* Relocating Allocator:: Waste less memory, if you can tolerate + automatic relocation of the blocks you get. + +Character Handling + +* Classification of Characters:: Testing whether characters are + letters, digits, punctuation, etc. + +* Case Conversion:: Case mapping, and the like. + +String and Array Utilities + +* Representation of Strings:: Introduction to basic concepts. +* String/Array Conventions:: Whether to use a string function or an + arbitrary array function. +* String Length:: Determining the length of a string. +* Copying and Concatenation:: Functions to copy the contents of strings + and arrays. +* String/Array Comparison:: Functions for byte-wise and character-wise + comparison. +* Collation Functions:: Functions for collating strings. +* Search Functions:: Searching for a specific element or substring. +* Finding Tokens in a String:: Splitting a string into tokens by looking + for delimiters. +* Encode Binary Data:: Encoding and Decoding of Binary Data. +* Argz and Envz Vectors:: Null-separated string vectors. + +Extended Characters + +* Extended Char Intro:: Multibyte codes versus wide characters. +* Locales and Extended Chars:: The locale selects the character codes. +* Multibyte Char Intro:: How multibyte codes are represented. +* Wide Char Intro:: How wide characters are represented. +* Wide String Conversion:: Converting wide strings to multibyte code + and vice versa. +* Length of Char:: how many bytes make up one multibyte char. +* Converting One Char:: Converting a string character by character. +* Example of Conversion:: Example showing why converting + one character at a time may be useful. +* Shift State:: Multibyte codes with "shift characters". + +Locales + +* Effects of Locale:: Actions affected by the choice of + locale. +* Choosing Locale:: How the user specifies a locale. +* Locale Categories:: Different purposes for which you can + select a locale. +* Setting the Locale:: How a program specifies the locale + with library functions. +* Standard Locales:: Locale names available on all systems. +* Numeric Formatting:: How to format numbers according to the + chosen locale. + +Message Translation + +* Message catalogs a la X/Open:: The @code{catgets} family of functions. +* The Uniforum approach:: The @code{gettext} family of functions. + +Searching and Sorting + +* Comparison Functions:: Defining how to compare two objects. + Since the sort and search facilities + are general, you have to specify the + ordering. +* Array Search Function:: The @code{bsearch} function. +* Array Sort Function:: The @code{qsort} function. +* Search/Sort Example:: An example program. +* Hash Search Function:: The @code{hsearch} function. +* Tree Search Function:: The @code{tsearch} function. + +Pattern Matching + +* Wildcard Matching:: Matching a wildcard pattern against a single string. +* Globbing:: Finding the files that match a wildcard pattern. +* Regular Expressions:: Matching regular expressions against strings. +* Word Expansion:: Expanding shell variables, nested commands, + arithmetic, and wildcards. + This is what the shell does with shell commands. + +I/O Overview + +* I/O Concepts:: Some basic information and terminology. +* File Names:: How to refer to a file. + +I/O on Streams + +* Streams:: About the data type representing a stream. +* Standard Streams:: Streams to the standard input and output + devices are created for you. +* Opening Streams:: How to create a stream to talk to a file. +* Closing Streams:: Close a stream when you are finished with it. +* Simple Output:: Unformatted output by characters and lines. +* Character Input:: Unformatted input by characters and words. +* Line Input:: Reading a line or a record from a stream. +* Unreading:: Peeking ahead/pushing back input just read. +* Block Input/Output:: Input and output operations on blocks of data. +* Formatted Output:: @code{printf} and related functions. +* Customizing Printf:: You can define new conversion specifiers for + @code{printf} and friends. +* Formatted Input:: @code{scanf} and related functions. +* EOF and Errors:: How you can tell if an I/O error happens. +* Binary Streams:: Some systems distinguish between text files + and binary files. +* File Positioning:: About random-access streams. +* Portable Positioning:: Random access on peculiar ISO C systems. +* Stream Buffering:: How to control buffering of streams. +* Other Kinds of Streams:: Streams that do not necessarily correspond + to an open file. +* Formatted Messages:: Print strictly formatted messages. + +Low-Level I/O + +* Opening and Closing Files:: How to open and close file + descriptors. +* Truncating Files:: Change the size of a file. +* I/O Primitives:: Reading and writing data. +* File Position Primitive:: Setting a descriptor's file + position. +* Descriptors and Streams:: Converting descriptor to stream + or vice-versa. +* Stream/Descriptor Precautions:: Precautions needed if you use both + descriptors and streams. +* Waiting for I/O:: How to check for input or output + on multiple file descriptors. +* Synchronizing I/O:: Making sure all I/O actions completed. +* Asynchronous I/O:: Perform I/O in parallel. +* Control Operations:: Various other operations on file + descriptors. +* Duplicating Descriptors:: Fcntl commands for duplicating + file descriptors. +* Descriptor Flags:: Fcntl commands for manipulating + flags associated with file + descriptors. +* File Status Flags:: Fcntl commands for manipulating + flags associated with open files. +* File Locks:: Fcntl commands for implementing + file locking. +* Interrupt Input:: Getting an asynchronous signal when + input arrives. + +File System Interface + +* Working Directory:: This is used to resolve relative + file names. +* Accessing Directories:: Finding out what files a directory + contains. +* Working on Directory Trees:: Apply actions to all files or a selectable + subset of a directory hierarchy. +* Hard Links:: Adding alternate names to a file. +* Symbolic Links:: A file that ``points to'' a file name. +* Deleting Files:: How to delete a file, and what that means. +* Renaming Files:: Changing a file's name. +* Creating Directories:: A system call just for creating a directory. +* File Attributes:: Attributes of individual files. +* Making Special Files:: How to create special files. +* Temporary Files:: Naming and creating temporary files. + +Pipes and FIFOs + +* Creating a Pipe:: Making a pipe with the @code{pipe} function. +* Pipe to a Subprocess:: Using a pipe to communicate with a + child process. +* FIFO Special Files:: Making a FIFO special file. +* Pipe Atomicity:: When pipe (or FIFO) I/O is atomic. + +Sockets + +* Socket Concepts:: Basic concepts you need to know about. +* Communication Styles::Stream communication, datagrams, and other styles. +* Socket Addresses:: How socket names (``addresses'') work. +* Interface Naming:: Identifying specific network interfaces. +* Local Namespace:: Details about the local namespace. +* Internet Namespace:: Details about the Internet namespace. +* Misc Namespaces:: Other namespaces not documented fully here. +* Open/Close Sockets:: Creating sockets and destroying them. +* Connections:: Operations on sockets with connection state. +* Datagrams:: Operations on datagram sockets. +* Inetd:: Inetd is a daemon that starts servers on request. + The most convenient way to write a server + is to make it work with Inetd. +* Socket Options:: Miscellaneous low-level socket options. +* Networks Database:: Accessing the database of network names. + +Low-Level Terminal Interface + +* Is It a Terminal:: How to determine if a file is a terminal + device, and what its name is. +* I/O Queues:: About flow control and typeahead. +* Canonical or Not:: Two basic styles of input processing. +* Terminal Modes:: How to examine and modify flags controlling + details of terminal I/O: echoing, + signals, editing. +* Line Control:: Sending break sequences, clearing + terminal buffers @dots{} +* Noncanon Example:: How to read single characters without echo. +* Pseudo-Terminals:: How to open a pseudo-terminal. + +Mathematics + +* Mathematical Constants:: Precise numeric values for often-used + constants. +* Trig Functions:: Sine, cosine, tangent, and friends. +* Inverse Trig Functions:: Arcsine, arccosine, etc. +* Exponents and Logarithms:: Also pow and sqrt. +* Hyperbolic Functions:: sinh, cosh, tanh, etc. +* Special Functions:: Bessel, gamma, erf. +* Pseudo-Random Numbers:: Functions for generating pseudo-random + numbers. +* FP Function Optimizations:: Fast code or small code. + +Arithmetic + +* Floating Point Numbers:: Basic concepts. IEEE 754. +* Floating Point Classes:: The five kinds of floating-point number. +* Floating Point Errors:: When something goes wrong in a calculation. +* Rounding:: Controlling how results are rounded. +* Control Functions:: Saving and restoring the FPU's state. +* Arithmetic Functions:: Fundamental operations provided by the library. +* Complex Numbers:: The types. Writing complex constants. +* Operations on Complex:: Projection, conjugation, decomposition. +* Integer Division:: Integer division with guaranteed rounding. +* Parsing of Numbers:: Converting strings to numbers. +* System V Number Conversion:: An archaic way to convert numbers to strings. + +Date and Time + +* Processor Time:: Measures processor time used by a program. +* 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. +* Resource Usage:: Measuring various resources used. +* Limits on Resources:: Specifying limits on resource usage. +* Priority:: Reading or setting process run priority. + +Non-Local Exits + +* Intro: Non-Local Intro. When and how to use these facilities. +* Details: Non-Local Details. Functions for nonlocal exits. +* Non-Local Exits and Signals:: Portability issues. + +Signal Handling + +* Concepts of Signals:: Introduction to the signal facilities. +* Standard Signals:: Particular kinds of signals with + standard names and meanings. +* Signal Actions:: Specifying what happens when a + particular signal is delivered. +* Defining Handlers:: How to write a signal handler function. +* Interrupted Primitives:: Signal handlers affect use of @code{open}, + @code{read}, @code{write} and other functions. +* Generating Signals:: How to send a signal to a process. +* Blocking Signals:: Making the system hold signals temporarily. +* Waiting for a Signal:: Suspending your program until a signal + arrives. +* Signal Stack:: Using a Separate Signal Stack. +* BSD Signal Handling:: Additional functions for backward + compatibility with BSD. + +Process Startup + +* Program Arguments:: Parsing your program's command-line arguments. +* Environment Variables:: How to access parameters inherited from + a parent process. +* Program Termination:: How to cause a process to terminate and + return status information to its parent. + +Processes + +* Running a Command:: The easy way to run another program. +* Process Creation Concepts:: An overview of the hard way to do it. +* Process Identification:: How to get the process ID of a process. +* Creating a Process:: How to fork a child process. +* Executing a File:: How to make a process execute another program. +* Process Completion:: How to tell when a child process has completed. +* Process Completion Status:: How to interpret the status value + returned from a child process. +* BSD Wait Functions:: More functions, for backward compatibility. +* Process Creation Example:: A complete example program. + +Job Control + +* Concepts of Job Control:: Jobs can be controlled by a shell. +* Job Control is Optional:: Not all POSIX systems support job control. +* Controlling Terminal:: How a process gets its controlling terminal. +* Access to the Terminal:: How processes share the controlling terminal. +* Orphaned Process Groups:: Jobs left after the user logs out. +* Implementing a Shell:: What a shell must do to implement job control. +* Functions for Job Control:: Functions to control process groups. + +Name Service Switch + +* NSS Basics:: What is this NSS good for. +* NSS Configuration File:: Configuring NSS. +* NSS Module Internals:: How does it work internally. +* Extending NSS:: What to do to add services or databases. + +Users and Groups + +* User and Group IDs:: Each user has a unique numeric ID; + likewise for groups. +* Process Persona:: The user IDs and group IDs of a process. +* Why Change Persona:: Why a program might need to change + its user and/or group IDs. +* How Change Persona:: Changing the user and group IDs. +* Reading Persona:: How to examine the user and group IDs. + +* Setting User ID:: Functions for setting the user ID. +* Setting Groups:: Functions for setting the group IDs. + +* Enable/Disable Setuid:: Turning setuid access on and off. +* Setuid Program Example:: The pertinent parts of one sample program. +* Tips for Setuid:: How to avoid granting unlimited access. + +* Who Logged In:: Getting the name of the user who logged in, + or of the real user ID of the current process. + +* User Accounting Database:: Keeping information about users and various + actions in databases. + +* User Database:: Functions and data structures for + accessing the user database. +* Group Database:: Functions and data structures for + accessing the group database. +* Database Example:: Example program showing the use of database + inquiry functions. +* Netgroup Database:: Functions for accessing the netgroup database. + +System Information + +* 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. +* Filesystem handling:: Which is mounted and/or available? + +System Configuration + +* General Limits:: Constants and functions that describe + various process-related limits that have + one uniform value for any given machine. +* System Options:: Optional POSIX features. +* Version Supported:: Version numbers of POSIX.1 and POSIX.2. +* Sysconf:: Getting specific configuration values + of general limits and system options. +* Minimums:: Minimum values for general limits. + +* Limits for Files:: Size limitations that pertain to individual files. + These can vary between file systems + or even from file to file. +* Options for Files:: Optional features that some files may support. +* File Minimums:: Minimum values for file limits. +* Pathconf:: Getting the limit values for a particular file. + +* Utility Limits:: Capacity limits of some POSIX.2 utility programs. +* Utility Minimums:: Minimum allowable values of those limits. + +* String Parameters:: Getting the default search path. + +POSIX Threads + +* Basic Thread Operations:: Creating, terminating, and waiting for threads. +* Thread Attributes:: Tuning thread scheduling. +* Cancellation:: Stopping a thread before it's done. +* Cleanup Handlers:: Deallocating resources when a thread is + cancelled. +* Mutexes:: One way to synchronize threads. +* Condition Variables:: Another way. +* POSIX Semaphores:: And a third way. +* Thread-Specific Data:: Variables with different values in + different threads. +* Threads and Signal Handling:: Why you should avoid mixing the two, and + how to do it if you must. +* Miscellaneous Thread Functions:: A grab bag of utility routines. + +Language Features + +* Consistency Checking:: Using @code{assert} to abort if + something ``impossible'' happens. +* Variadic Functions:: Defining functions with varying numbers + of args. +* Null Pointer Constant:: The macro @code{NULL}. +* Important Data Types:: Data types for object sizes. +* Data Type Measurements:: Parameters of data type representations. + +Installation + +* Tools for Installation:: We recommend using these tools to build. +* Supported Configurations:: What systems the GNU C library runs on. +* Tips for Installation:: Useful hints for the installation. +* Reporting Bugs:: How to report bugs (if you want to + get them fixed) and other troubles + you may have with the GNU C library. + +Maintenance + +* Source Layout:: How to add new functions or header files + to the GNU C library. +* Porting:: How to port the GNU C library to + a new machine or operating system. +@end menu diff --git a/manual/users.texi b/manual/users.texi index 5ffd5fd..562390c 100644 --- a/manual/users.texi +++ b/manual/users.texi @@ -1,4 +1,5 @@ -@node Users and Groups +@node Users and Groups, System Information, Name Service Switch, Top +@c %MENU% How users are identified and classified @chapter Users and Groups Every user who can log in on the system is identified by a unique number diff --git a/sysdeps/unix/sysv/linux/i386/dl-procinfo.h b/sysdeps/unix/sysv/linux/i386/dl-procinfo.h index 4520e6c..77c859b 100644 --- a/sysdeps/unix/sysv/linux/i386/dl-procinfo.h +++ b/sysdeps/unix/sysv/linux/i386/dl-procinfo.h @@ -27,8 +27,8 @@ static const char x86_cap_flags[][7] = { "fpu", "vme", "de", "pse", "tsc", "msr", "pae", "mce", "cx8", "apic", "10", "sep", "mtrr", "pge", "mca", "cmov", - "fcmov", "17", "18", "19", "20", "21", "22", "mmx", - "osfxsr", "25", "26", "27", "28", "29", "30", "amd3d" + "pat", "pse36", "18", "19", "20", "21", "22", "mmx", + "fxsr", "25", "26", "27", "28", "29", "30", "amd3d" }; static inline int diff --git a/sysdeps/unix/sysv/linux/recvmsg.c b/sysdeps/unix/sysv/linux/recvmsg.c index 14a3417..3795d91 100644 --- a/sysdeps/unix/sysv/linux/recvmsg.c +++ b/sysdeps/unix/sysv/linux/recvmsg.c @@ -35,10 +35,7 @@ struct __kernel_ucred extern int __syscall_recvmsg (int, struct msghdr *, int); int -__libc_recvmsg (fd, message, flags) - int fd; - struct msghdr *message; - int flags; +__libc_recvmsg (int fd, struct msghdr *message, int flags) { struct cmsghdr *cm; int ret; diff --git a/sysdeps/unix/sysv/linux/sendmsg.c b/sysdeps/unix/sysv/linux/sendmsg.c index bc12b05..273add9 100644 --- a/sysdeps/unix/sysv/linux/sendmsg.c +++ b/sysdeps/unix/sysv/linux/sendmsg.c @@ -37,10 +37,7 @@ extern int __syscall_sendmsg (int, const struct msghdr *, int); /* Send a message described by MESSAGE on socket FD. Returns the number of bytes sent, or -1 for errors. */ int -__libc_sendmsg (fd, message, flags) - int fd; - const struct msghdr *message; - int flags; +__libc_sendmsg (int fd, const struct msghdr *message, int flags) { struct cmsghdr *cm; struct cmsgcred *cc; -- 2.7.4