This is libc.info, produced by makeinfo version 4.0 from libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.09 DRAFT, last updated 28 Aug 1999, of `The GNU C
Library Reference Manual', for Version 2.2 Beta.

   Copyright (C) 1993, '94, '95, '96, '97, '98, '99 Free Software
Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU Library General Public License" is
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the text of the translation of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.


File: libc.info,  Node: crypt,  Next: DES Encryption,  Prev: getpass,  Up: Cryptographic Functions

Encrypting Passwords
====================

 - Function: char * crypt (const char *KEY, const char *SALT)
     The `crypt' function takes a password, KEY, as a string, and a
     SALT character array which is described below, and returns a
     printable ASCII string which starts with another salt.  It is
     believed that, given the output of the function, the best way to
     find a KEY that will produce that output is to guess values of KEY
     until the original value of KEY is found.

     The SALT parameter does two things.  Firstly, it selects which
     algorithm is used, the MD5-based one or the DES-based one.
     Secondly, it makes life harder for someone trying to guess
     passwords against a file containing many passwords; without a
     SALT, an intruder can make a guess, run `crypt' on it once, and
     compare the result with all the passwords.  With a SALT, the
     intruder must run `crypt' once for each different salt.

     For the MD5-based algorithm, the SALT should consist of the string
     `$1$', followed by up to 8 characters, terminated by either
     another `$' or the end of the string.  The result of `crypt' will
     be the SALT, followed by a `$' if the salt didn't end with one,
     followed by 22 characters from the alphabet `./0-9A-Za-z', up to
     34 characters total.  Every character in the KEY is significant.

     For the DES-based algorithm, the SALT should consist of two
     characters from the alphabet `./0-9A-Za-z', and the result of
     `crypt' will be those two characters followed by 11 more from the
     same alphabet, 13 in total.  Only the first 8 characters in the
     KEY are significant.

     The MD5-based algorithm has no limit on the useful length of the
     password used, and is slightly more secure.  It is therefore
     preferred over the DES-based algorithm.

     When the user enters their password for the first time, the SALT
     should be set to a new string which is reasonably random.  To
     verify a password against the result of a previous call to
     `crypt', pass the result of the previous call as the SALT.

   The following short program is an example of how to use `crypt' the
first time a password is entered.  Note that the SALT generation is
just barely acceptable; in particular, it is not unique between
machines, and in many applications it would not be acceptable to let an
attacker know what time the user's password was last set.

     #include <stdio.h>
     #include <time.h>
     #include <unistd.h>
     #include <crypt.h>
     
     int
     main(void)
     {
       unsigned long seed[2];
       char salt[] = "$1$........";
       const char *const seedchars =
         "./0123456789ABCDEFGHIJKLMNOPQRST"
         "UVWXYZabcdefghijklmnopqrstuvwxyz";
       char *password;
       int i;
     
       /* Generate a (not very) random seed.
          You should do it better than this... */
       seed[0] = time(NULL);
       seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000);
     
       /* Turn it into printable characters from `seedchars'. */
       for (i = 0; i < 8; i++)
         salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f];
     
       /* Read in the user's password and encrypt it. */
       password = crypt(getpass("Password:"), salt);
     
       /* Print the results. */
       puts(password);
       return 0;
     }

   The next program shows how to verify a password.  It prompts the user
for a password and prints "Access granted." if the user types `GNU libc
manual'.

     #include <stdio.h>
     #include <string.h>
     #include <unistd.h>
     #include <crypt.h>
     
     int
     main(void)
     {
       /* Hashed form of "GNU libc manual". */
       const char *const pass = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/";
     
       char *result;
       int ok;
     
       /* Read in the user's password and encrypt it,
          passing the expected password in as the salt. */
       result = crypt(getpass("Password:"), pass);
     
       /* Test the result. */
       ok = strcmp (result, pass) == 0;
     
       puts(ok ? "Access granted." : "Access denied.");
       return ok ? 0 : 1;
     }

 - Function: char * crypt_r (const char *KEY, const char *SALT, struct
          crypt_data * DATA)
     The `crypt_r' function does the same thing as `crypt', but takes
     an extra parameter which includes space for its result (among
     other things), so it can be reentrant.  `data->initialized' must be
     cleared to zero before the first time `crypt_r' is called.

     The `crypt_r' function is a GNU extension.

   The `crypt' and `crypt_r' functions are prototyped in the header
`crypt.h'.


File: libc.info,  Node: DES Encryption,  Prev: crypt,  Up: Cryptographic Functions

DES Encryption
==============

   The Data Encryption Standard is described in the US Government
Federal Information Processing Standards (FIPS) 46-3 published by the
National Institute of Standards and Technology.  The DES has been very
thoroughly analysed since it was developed in the late 1970s, and no new
significant flaws have been found.

   However, the DES uses only a 56-bit key (plus 8 parity bits), and a
machine has been built in 1998 which can search through all possible
keys in about 6 days, which cost about US$200000; faster searches would
be possible with more money.  This makes simple DES unsecure for most
purposes, and NIST no longer permits new US government systems to use
simple DES.

   For serious encryption functionality, it is recommended that one of
the many free encryption libraries be used instead of these routines.

   The DES is a reversible operation which takes a 64-bit block and a
64-bit key, and produces another 64-bit block.  Usually the bits are
numbered so that the most-significant bit, the first bit, of each block
is numbered 1.

   Under that numbering, every 8th bit of the key (the 8th, 16th, and so
on) is not used by the encryption algorithm itself.  But the key must
have odd parity; that is, out of bits 1 through 8, and 9 through 16, and
so on, there must be an odd number of `1' bits, and this completely
specifies the unused bits.

 - Function: void setkey (const char *KEY)
     The `setkey' function sets an internal data structure to be an
     expanded form of KEY.  KEY is specified as an array of 64 bits
     each stored in a `char', the first bit is `key[0]' and the 64th
     bit is `key[63]'.  The KEY should have the correct parity.

 - Function: void encrypt (char *BLOCK, int EDFLAG)
     The `encrypt' function encrypts BLOCK if EDFLAG is 0, otherwise it
     decrypts BLOCK, using a key previously set by `setkey'.  The
     result is placed in BLOCK.

     Like `setkey', BLOCK is specified as an array of 64 bits each
     stored in a `char', but there are no parity bits in BLOCK.

 - Function: void setkey_r (const char *KEY, struct crypt_data * DATA)
 - Function: void encrypt_r (char *BLOCK, int EDFLAG, struct crypt_data
          * DATA)
     These are reentrant versions of `setkey' and `encrypt'.  The only
     difference is the extra parameter, which stores the expanded
     version of KEY.  Before calling `setkey_r' the first time,
     `data->initialised' must be cleared to zero.

   The `setkey_r' and `encrypt_r' functions are GNU extensions.
`setkey', `encrypt', `setkey_r', and `encrypt_r' are defined in
`crypt.h'.

 - Function: int ecb_crypt (char *KEY, char *BLOCKS, unsigned LEN,
          unsigned MODE)
     The function `ecb_crypt' encrypts or decrypts one or more blocks
     using DES.  Each block is encrypted independently.

     The BLOCKS and the KEY are stored packed in 8-bit bytes, so that
     the first bit of the key is the most-significant bit of `key[0]'
     and the 63rd bit of the key is stored as the least-significant bit
     of `key[7]'.  The KEY should have the correct parity.

     LEN is the number of bytes in BLOCKS.  It should be a multiple of
     8 (so that there is a whole number of blocks to encrypt).  LEN is
     limited to a maximum of `DES_MAXDATA' bytes.

     The result of the encryption replaces the input in BLOCKS.

     The MODE parameter is the bitwise OR of two of the following:

    `DES_ENCRYPT'
          This constant, used in the MODE parameter, specifies that
          BLOCKS is to be encrypted.

    `DES_DECRYPT'
          This constant, used in the MODE parameter, specifies that
          BLOCKS is to be decrypted.

    `DES_HW'
          This constant, used in the MODE parameter, asks to use a
          hardware device.  If no hardware device is available,
          encryption happens anyway, but in software.

    `DES_SW'
          This constant, used in the MODE parameter, specifies that no
          hardware device is to be used.

     The result of the function will be one of these values:

    `DESERR_NONE'
          The encryption succeeded.

    `DESERR_NOHWDEVICE'
          The encryption succeeded, but there was no hardware device
          available.

    `DESERR_HWERROR'
          The encryption failed because of a hardware problem.

    `DESERR_BADPARAM'
          The encryption failed because of a bad parameter, for
          instance LEN is not a multiple of 8 or LEN is larger than
          `DES_MAXDATA'.

 - Function: int DES_FAILED (int ERR)
     This macro returns 1 if ERR is a `success' result code from
     `ecb_crypt' or `cbc_crypt', and 0 otherwise.

 - Function: int cbc_crypt (char *KEY, char *BLOCKS, unsigned LEN,
          unsigned MODE, char *IVEC)
     The function `cbc_crypt' encrypts or decrypts one or more blocks
     using DES in Cipher Block Chaining mode.

     For encryption in CBC mode, each block is exclusive-ored with IVEC
     before being encrypted, then IVEC is replaced with the result of
     the encryption, then the next block is processed.  Decryption is
     the reverse of this process.

     This has the advantage that blocks which are the same before being
     encrypted are very unlikely to be the same after being encrypted,
     making it much harder to detect patterns in the data.

     Usually, IVEC is set to 8 random bytes before encryption starts.
     Then the 8 random bytes are transmitted along with the encrypted
     data (without themselves being encrypted), and passed back in as
     IVEC for decryption.  Another possibility is to set IVEC to 8
     zeroes initially, and have the first the block encrypted consist
     of 8 random bytes.

     Otherwise, all the parameters are similar to those for `ecb_crypt'.

 - Function: void des_setparity (char *KEY)
     The function `des_setparity' changes the 64-bit KEY, stored packed
     in 8-bit bytes, to have odd parity by altering the low bits of
     each byte.

   The `ecb_crypt', `cbc_crypt', and `des_setparity' functions and
their accompanying macros are all defined in the header
`rpc/des_crypt.h'.


File: libc.info,  Node: Debugging Support,  Next: POSIX Threads,  Prev: Cryptographic Functions,  Up: Top

Debugging support
*****************

   Applications are usually debugged using dedicated debugger programs.
But sometimes this is not possible and, in any case, it is useful to
provide the developer with as much information as possible at the time
the problems are experienced.  For this reason a few functions are
provided which a program can use to help the developer more easily
locate the problem.

* Menu:

* Backtraces::                Obtaining and printing a back trace of the
                               current stack.


File: libc.info,  Node: Backtraces,  Up: Debugging Support

Backtraces
==========

   A "backtrace" is a list of the function calls that are currently
active in a thread.  The usual way to inspect a backtrace of a program
is to use an external debugger such as gdb.  However, sometimes it is
useful to obtain a backtrace programatically from within a program,
e.g., for the purposes of logging or diagnostics.

   The header file `execinfo.h' declares three functions that obtain
and manipulate backtraces of the current thread.

 - Function: int backtrace (void **BUFFER, int SIZE)
     The `backtrace' function obtains a backtrace for the current
     thread, as a list of pointers, and places the information into
     BUFFER.  The argument SIZE should be the number of `void *'
     elements that will fit into BUFFER.  The return value is the
     actual number of entries of BUFFER that are obtained, and is at
     most SIZE.

     The pointers placed in BUFFER are actually return addresses
     obtained by inspecting the stack, one return address per stack
     frame.

     Note that certain compiler optimisations may interfere with
     obtaining a valid backtrace.  Function inlining causes the inlined
     function to not have a stack frame; tail call optimisation
     replaces one stack frame with another; frame pointer elimination
     will stop `backtrace' from interpreting the stack contents
     correctly.

 - Function: char ** backtrace_symbols (void *const *BUFFER, int SIZE)
     The `backtrace_symbols' function translates the information
     obtained from the `backtrace' function into an array of strings.
     The argument BUFFER should be a pointer to an array of addresses
     obtained via the `backtrace' function, and SIZE is the number of
     entries in that array (the return value of `backtrace').

     The return value is a pointer to an array of strings, which has
     SIZE entries just like the array BUFFER.  Each string contains a
     printable representation of the corresponding element of BUFFER.
     It includes the function name (if this can be determined), an
     offset into the function, and the actual return address (in
     hexadecimal).

     Currently, the function name and offset only be obtained on
     systems that use the ELF binary format for programs and libraries.
     On other systems, only the hexadecimal return address will be
     present.  Also, you may need to pass additional flags to the
     linker to make the function names available to the program.  (For
     example, on systems using GNU ld, you must pass (`-rdynamic'.)

     The return value of `backtrace_symbols' is a pointer obtained via
     the `malloc' function, and it is the responsibility of the caller
     to `free' that pointer.  Note that only the return value need be
     freed, not the individual strings.

     The return value is `NULL' if sufficient memory for the strings
     cannot be obtained.

 - Function: void backtrace_symbols_fd (void *const *BUFFER, int SIZE,
          int FD)
     The `backtrace_symbols_fd' function performs the same translation
     as the function `backtrace_symbols' function.  Instead of returning
     the strings to the caller, it writes the strings to the file
     descriptor FD, one per line.  It does not use the `malloc'
     function, and can therefore be used in situations where that
     function might fail.

   The following program illustrates the use of these functions.  Note
that the array to contain the return addresses returned by `backtrace'
is allocated on the stack.  Therefore code like this can be used in
situations where the memory handling via `malloc' does not work anymore
(in which case the `backtrace_symbols' has to be replaced by a
`backtrace_symbols_fd' call as well).  The number of return addresses
is normally not very large.  Even complicated programs rather seldom
have a nesting level of more than, say, 50 and with 200 possible
entries probably all programs should be covered.

     #include <execinfo.h>
     #include <stdio.h>
     #include <stdlib.h>
     
     /* Obtain a backtrace and print it to `stdout'. */
     void
     print_trace (void)
     {
       void *array[10];
       size_t size;
       char **strings;
       size_t i;
     
       size = backtrace (array, 10);
       strings = backtrace_symbols (array, size);
     
       printf ("Obtained %zd stack frames.\n", size);
     
       for (i = 0; i < size; i++)
          printf ("%s\n", strings[i]);
     
       free (strings);
     }
     
     /* A dummy function to make the backtrace more interesting. */
     void
     dummy_function (void)
     {
       print_trace ();
     }
     
     int
     main (void)
     {
       dummy_function ();
       return 0;
     }


File: libc.info,  Node: POSIX Threads,  Next: Language Features,  Prev: Debugging Support,  Up: Top

POSIX Threads
*************

   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 (`pthread_*') do not use ERRNO.  Instead they
return an error code directly.  The semaphore operations do use 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.
* Threads and Fork::            Interactions between threads and the
                                  `fork' function.
* Streams and Fork::            Interactions between stdio streams and
                                  `fork'.
* Miscellaneous Thread Functions:: A grab bag of utility routines.


File: libc.info,  Node: Basic Thread Operations,  Next: Thread Attributes,  Up: POSIX Threads

Basic Thread Operations
=======================

   These functions are the thread equivalents of `fork', `exit', and
`wait'.

 - Function: int pthread_create (pthread_t * THREAD, pthread_attr_t *
          ATTR, void * (*START_ROUTINE)(void *), void * ARG)
     `pthread_create' creates a new thread of control that executes
     concurrently with the calling thread. The new thread calls the
     function START_ROUTINE, passing it ARG as first argument. The new
     thread terminates either explicitly, by calling `pthread_exit', or
     implicitly, by returning from the START_ROUTINE function. The
     latter case is equivalent to calling `pthread_exit' with the result
     returned by START_ROUTINE as exit code.

     The ATTR argument specifies thread attributes to be applied to the
     new thread. *Note Thread Attributes::, for details. The ATTR
     argument can also be `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 THREAD argument, and a 0 is
     returned. On error, a non-zero error code is returned.

     This function may return the following errors:
    `EAGAIN'
          Not enough system resources to create a process for the new
          thread, or more than `PTHREAD_THREADS_MAX' threads are
          already active.

 - Function: void pthread_exit (void *RETVAL)
     `pthread_exit' terminates the execution of the calling thread.  All
     cleanup handlers (*note Cleanup Handlers::) that have been set for
     the calling thread with `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-`NULL' values associated with
     them in the calling thread (*note Thread-Specific Data::).
     Finally, execution of the calling thread is stopped.

     The RETVAL argument is the return value of the thread. It can be
     retrieved from another thread using `pthread_join'.

     The `pthread_exit' function never returns.

 - Function: int pthread_cancel (pthread_t THREAD)
     `pthread_cancel' sends a cancellation request to the thread denoted
     by the THREAD argument.  If there is no such thread,
     `pthread_cancel' fails and returns `ESRCH'.  Otherwise it returns
     0. *Note Cancellation::, for details.

 - Function: int pthread_join (pthread_t TH, void **thread_RETURN)
     `pthread_join' suspends the execution of the calling thread until
     the thread identified by TH terminates, either by calling
     `pthread_exit' or by being cancelled.

     If THREAD_RETURN is not `NULL', the return value of TH is stored
     in the location pointed to by THREAD_RETURN.  The return value of
     TH is either the argument it gave to `pthread_exit', or
     `PTHREAD_CANCELED' if TH was cancelled.

     The joined thread `th' must be in the joinable state: it must not
     have been detached using `pthread_detach' or the
     `PTHREAD_CREATE_DETACHED' attribute to `pthread_create'.

     When a joinable thread terminates, its memory resources (thread
     descriptor and stack) are not deallocated until another thread
     performs `pthread_join' on it. Therefore, `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 `pthread_join' on a thread TH on which another thread is
     already waiting for termination returns an error.

     `pthread_join' is a cancellation point. If a thread is canceled
     while suspended in `pthread_join', the thread execution resumes
     immediately and the cancellation is executed without waiting for
     the TH thread to terminate. If cancellation occurs during
     `pthread_join', the TH thread remains not joined.

     On success, the return value of TH is stored in the location
     pointed to by THREAD_RETURN, and 0 is returned. On error, one of
     the following values is returned:
    `ESRCH'
          No thread could be found corresponding to that specified by
          TH.

    `EINVAL'
          The TH thread has been detached, or another thread is already
          waiting on termination of TH.

    `EDEADLK'
          The TH argument refers to the calling thread.


File: libc.info,  Node: Thread Attributes,  Next: Cancellation,  Prev: Basic Thread Operations,  Up: POSIX Threads

Thread Attributes
=================

   Threads have a number of attributes that may be set at creation time.
This is done by filling a thread attribute object ATTR of type
`pthread_attr_t', then passing it as second argument to
`pthread_create'. Passing `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 `pthread_create' does not
change the attributes of the thread previously created.

 - Function: int pthread_attr_init (pthread_attr_t *ATTR)
     `pthread_attr_init' initializes the thread attribute object ATTR
     and fills it with default values for the attributes. (The default
     values are listed below for each attribute.)

     Each attribute ATTRNAME (see below for a list of all attributes)
     can be individually set using the function
     `pthread_attr_setATTRNAME' and retrieved using the function
     `pthread_attr_getATTRNAME'.

 - Function: int pthread_attr_destroy (pthread_attr_t *ATTR)
     `pthread_attr_destroy' destroys the attribute object pointed to by
     ATTR releasing any resources associated with it.  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.

 - Function: int pthread_attr_setattr (pthread_attr_t *OBJ, int VALUE)
     Set attribute ATTR to VALUE in the attribute object pointed to by
     OBJ.  See below for a list of possible attributes and the values
     they can take.

     On success, these functions return 0.  If VALUE is not meaningful
     for the ATTR being modified, they will return the error code
     `EINVAL'.  Some of the functions have other failure modes; see
     below.

 - Function: int pthread_attr_getattr (const pthread_attr_t *OBJ, int
          *VALUE)
     Store the current setting of ATTR in OBJ into the variable pointed
     to by VALUE.

     These functions always return 0.

   The following thread attributes are supported:
`detachstate'
     Choose whether the thread is created in the joinable state (value
     `PTHREAD_CREATE_JOINABLE') or in the detached state
     (`PTHREAD_CREATE_DETACHED').  The default is
     `PTHREAD_CREATE_JOINABLE'.

     In the joinable state, another thread can synchronize on the thread
     termination and recover its termination code using `pthread_join',
     but some of the thread resources are kept allocated after the
     thread terminates, and reclaimed only when another thread performs
     `pthread_join' on that thread.

     In the detached state, the thread resources are immediately freed
     when it terminates, but `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 `pthread_detach'.

`schedpolicy'
     Select the scheduling policy for the thread: one of `SCHED_OTHER'
     (regular, non-realtime scheduling), `SCHED_RR' (realtime,
     round-robin) or `SCHED_FIFO' (realtime, first-in first-out).  The
     default is `SCHED_OTHER'.

     The realtime scheduling policies `SCHED_RR' and `SCHED_FIFO' are
     available only to processes with superuser privileges.
     `pthread_attr_setschedparam' will fail and return `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 `pthread_setschedparam'.

`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
     `SCHED_OTHER'; it only matters for the realtime policies
     `SCHED_RR' and `SCHED_FIFO'.

     The scheduling priority of a thread can be changed after creation
     with `pthread_setschedparam'.

`inheritsched'
     Choose whether the scheduling policy and scheduling parameter for
     the newly created thread are determined by the values of the
     SCHEDPOLICY and SCHEDPARAM attributes (value
     `PTHREAD_EXPLICIT_SCHED') or are inherited from the parent thread
     (value `PTHREAD_INHERIT_SCHED').  The default is
     `PTHREAD_EXPLICIT_SCHED'.

`scope'
     Choose the scheduling contention scope for the created thread.  The
     default is `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, `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.

     `PTHREAD_SCOPE_PROCESS' is not supported in LinuxThreads.  If you
     try to set the scope to this value, `pthread_attr_setscope' will
     fail and return `ENOTSUP'.

`stackaddr'
     Provide an address for an application managed stack.  The size of
     the stack must be at least `PTHREAD_STACK_MIN'.

`stacksize'
     Change the size of the stack created for the thread.  The value
     defines the minimum stack size, in bytes.

     If the value exceeds the system's maximum stack size, or is smaller
     than `PTHREAD_STACK_MIN', `pthread_attr_setstacksize' will fail
     and return `EINVAL'.

`stack'
     Provide both the address and size of an application managed stack
     to use for the new thread.  The base of the memory area is
     STACKADDR with the size of the memory area, STACKSIZE, measured in
     bytes.

     If the value of STACKSIZE is less than `PTHREAD_STACK_MIN', or
     greater than the system's maximum stack size, or if the value of
     STACKADDR lacks the proper alignment, `pthread_attr_setstack' will
     fail and return `EINVAL'.

`guardsize'
     Change the minimum size in bytes of the guard area for the thread's
     stack.  The default size is a single page.  If this value is set,
     it will be rounded up to the nearest page size.  If the value is
     set to 0, a guard area will not be created for this thread.  The
     space allocated for the guard area is used to catch stack
     overflow.  Therefore, when allocating large structures on the
     stack, a larger guard area may be required to catch a stack
     overflow.

     If the caller is managing their own stacks (if the `stackaddr'
     attribute has been set), then the `guardsize' attribute is ignored.

     If the value exceeds the `stacksize', `pthread_atrr_setguardsize'
     will fail and return `EINVAL'.


File: libc.info,  Node: Cancellation,  Next: Cleanup Handlers,  Prev: Thread Attributes,  Up: POSIX Threads

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 `pthread_create', they always defer cancellation
requests.

   When a thread eventually honors a cancellation request, it behaves
as if `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
`PTHREAD_CANCELED' is provided to whichever thread calls PTHREAD_JOIN
on it. See `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 `pthread_join', `pthread_cond_wait',
`pthread_cond_timedwait', `pthread_testcancel', `sem_wait', and
`sigwait' are cancellation points.  In addition, these system calls are
cancellation points:

accept                   open                     sendmsg
close                    pause                    sendto
connect                  read                     system
fcntl                    recv                     tcdrain
fsync                    recvfrom                 wait
lseek                    recvmsg                  waitpid
msync                    send                     write
nanosleep                                         

All library functions that call these functions (such as `printf') are
also cancellation points.

 - Function: int pthread_setcancelstate (int STATE, int *OLDSTATE)
     `pthread_setcancelstate' changes the cancellation state for the
     calling thread - that is, whether cancellation requests are
     ignored or not. The STATE argument is the new cancellation state:
     either `PTHREAD_CANCEL_ENABLE' to enable cancellation, or
     `PTHREAD_CANCEL_DISABLE' to disable cancellation (cancellation
     requests are ignored).

     If OLDSTATE is not `NULL', the previous cancellation state is
     stored in the location pointed to by OLDSTATE, and can thus be
     restored later by another call to `pthread_setcancelstate'.

     If the STATE argument is not `PTHREAD_CANCEL_ENABLE' or
     `PTHREAD_CANCEL_DISABLE', `pthread_setcancelstate' fails and
     returns `EINVAL'.  Otherwise it returns 0.

 - Function: int pthread_setcanceltype (int TYPE, int *OLDTYPE)
     `pthread_setcanceltype' changes the type of responses to
     cancellation requests for the calling thread: asynchronous
     (immediate) or deferred.  The TYPE argument is the new
     cancellation type: either `PTHREAD_CANCEL_ASYNCHRONOUS' to cancel
     the calling thread as soon as the cancellation request is
     received, or `PTHREAD_CANCEL_DEFERRED' to keep the cancellation
     request pending until the next cancellation point. If OLDTYPE is
     not `NULL', the previous cancellation state is stored in the
     location pointed to by OLDTYPE, and can thus be restored later by
     another call to `pthread_setcanceltype'.

     If the TYPE argument is not `PTHREAD_CANCEL_DEFERRED' or
     `PTHREAD_CANCEL_ASYNCHRONOUS', `pthread_setcanceltype' fails and
     returns `EINVAL'.  Otherwise it returns 0.

 - Function: void pthread_testcancel (VOID)
     `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.


File: libc.info,  Node: Cleanup Handlers,  Next: Mutexes,  Prev: Cancellation,  Up: POSIX Threads

Cleanup Handlers
================

   Cleanup handlers are functions that get called when a thread
terminates, either by calling `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
`malloc' or close file descriptors on thread termination.

   Here is how to lock a mutex MUT in such a way that it will be
unlocked if the thread is canceled while MUT is locked:

     pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
     pthread_mutex_lock(&mut);
     /* do some work */
     pthread_mutex_unlock(&mut);
     pthread_cleanup_pop(0);

   Equivalently, the last two lines can be replaced by

     pthread_cleanup_pop(1);

   Notice that the code above is safe only in deferred cancellation mode
(see `pthread_setcanceltype'). In asynchronous cancellation mode, a
cancellation can occur between `pthread_cleanup_push' and
`pthread_mutex_lock', or between `pthread_mutex_unlock' and
`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:

     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);

   The code above can be rewritten in a more compact and efficient way,
using the non-portable functions `pthread_cleanup_push_defer_np' and
`pthread_cleanup_pop_restore_np':

     pthread_cleanup_push_defer_np(pthread_mutex_unlock, (void *) &mut);
     pthread_mutex_lock(&mut);
     /* do some work */
     pthread_cleanup_pop_restore_np(1);

 - Function: void pthread_cleanup_push (void (*ROUTINE) (void *), void
          *ARG)
     `pthread_cleanup_push' installs the ROUTINE function with argument
     ARG as a cleanup handler. From this point on to the matching
     `pthread_cleanup_pop', the function ROUTINE will be called with
     arguments ARG when the thread terminates, either through
     `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.

 - Function: void pthread_cleanup_pop (int EXECUTE)
     `pthread_cleanup_pop' removes the most recently installed cleanup
     handler. If the EXECUTE argument is not 0, it also executes the
     handler, by calling the ROUTINE function with arguments ARG. If
     the EXECUTE argument is 0, the handler is only removed but not
     executed.

   Matching pairs of `pthread_cleanup_push' and `pthread_cleanup_pop'
must occur in the same function, at the same level of block nesting.
Actually, `pthread_cleanup_push' and `pthread_cleanup_pop' are macros,
and the expansion of `pthread_cleanup_push' introduces an open brace
`{' with the matching closing brace `}' being introduced by the
expansion of the matching `pthread_cleanup_pop'.

 - Function: void pthread_cleanup_push_defer_np (void (*ROUTINE) (void
          *), void *ARG)
     `pthread_cleanup_push_defer_np' is a non-portable extension that
     combines `pthread_cleanup_push' and `pthread_setcanceltype'.  It
     pushes a cleanup handler just as `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.

 - Function: void pthread_cleanup_pop_restore_np (int EXECUTE)
     `pthread_cleanup_pop_restore_np' pops a cleanup handler introduced
     by `pthread_cleanup_push_defer_np', and restores the cancellation
     type to its value at the time `pthread_cleanup_push_defer_np' was
     called.

   `pthread_cleanup_push_defer_np' and `pthread_cleanup_pop_restore_np'
must occur in matching pairs, at the same level of block nesting.

   The sequence

     pthread_cleanup_push_defer_np(routine, arg);
     ...
     pthread_cleanup_pop_defer_np(execute);

is functionally equivalent to (but more compact and efficient than)

     {
       int oldtype;
       pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
       pthread_cleanup_push(routine, arg);
       ...
       pthread_cleanup_pop(execute);
       pthread_setcanceltype(oldtype, NULL);
     }


File: libc.info,  Node: Mutexes,  Next: Condition Variables,  Prev: Cleanup Handlers,  Up: POSIX Threads

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
`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 `pthread_mutex_lock' or `pthread_mutex_unlock' from
a signal handler may deadlock the calling thread.

 - Function: int pthread_mutex_init (pthread_mutex_t *MUTEX, const
          pthread_mutexattr_t *MUTEXATTR)
     `pthread_mutex_init' initializes the mutex object pointed to by
     MUTEX according to the mutex attributes specified in MUTEXATTR.
     If MUTEXATTR is `NULL', default attributes are used instead.

     The LinuxThreads implementation supports only one mutex attribute,
     the MUTEX TYPE, which is either "fast", "recursive", or "error
     checking". The type of a mutex determines whether it can be locked
     again by a thread that already owns it.  The default type is
     "fast".

     Variables of type `pthread_mutex_t' can also be initialized
     statically, using the constants `PTHREAD_MUTEX_INITIALIZER' (for
     timed mutexes), `PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP' (for
     recursive mutexes), `PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP' (for
     fast mutexes(, and `PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP' (for
     error checking mutexes).

     `pthread_mutex_init' always returns 0.

 - Function: int pthread_mutex_lock (pthread_mutex_t *mutex))
     `pthread_mutex_lock' locks the given mutex. If the mutex is
     currently unlocked, it becomes locked and owned by the calling
     thread, and `pthread_mutex_lock' returns immediately. If the mutex
     is already locked by another thread, `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 `pthread_mutex_lock' depends on the type of the mutex. If the
     mutex is of the "fast" type, 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" type,
     `pthread_mutex_lock' returns immediately with the error code
     `EDEADLK'.  If the mutex is of the "recursive" type,
     `pthread_mutex_lock' succeeds and returns immediately, recording
     the number of times the calling thread has locked the mutex. An
     equal number of `pthread_mutex_unlock' operations must be
     performed before the mutex returns to the unlocked state.

 - Function: int pthread_mutex_trylock (pthread_mutex_t *MUTEX)
     `pthread_mutex_trylock' behaves identically to
     `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,
     `pthread_mutex_trylock' returns immediately with the error code
     `EBUSY'.

 - Function: int pthread_mutex_timedlock (pthread_mutex_t *MUTEX, const
          struct timespec *ABSTIME)
     The `pthread_mutex_timedlock' is similar to the
     `pthread_mutex_lock' function but instead of blocking for in
     indefinite time if the mutex is locked by another thread, it
     returns when the time specified in ABSTIME is reached.

     This function can only be used on standard ("timed") and "error
     checking" mutexes.  It behaves just like `pthread_mutex_lock' for
     all other types.

     If the mutex is successfully locked, the function returns zero.
     If the time specified in ABSTIME is reached without the mutex
     being locked, `ETIMEDOUT' is returned.

     This function was introduced in the POSIX.1d revision of the POSIX
     standard.

 - Function: int pthread_mutex_unlock (pthread_mutex_t *MUTEX)
     `pthread_mutex_unlock' unlocks the given mutex. The mutex is
     assumed to be locked and owned by the calling thread on entrance to
     `pthread_mutex_unlock'. If the mutex is of the "fast" type,
     `pthread_mutex_unlock' always returns it to the unlocked state. If
     it is of the "recursive" type, it decrements the locking count of
     the mutex (number of `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, `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
     `pthread_mutex_unlock'.  If these conditions are not met,
     `pthread_mutex_unlock' returns `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.

 - Function: int pthread_mutex_destroy (pthread_mutex_t *MUTEX)
     `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 `pthread_mutex_destroy' actually does
     nothing except checking that the mutex is unlocked.

     If the mutex is locked by some thread, `pthread_mutex_destroy'
     returns `EBUSY'.  Otherwise it returns 0.

   If any of the above functions (except `pthread_mutex_init') is
applied to an uninitialized mutex, they will simply return `EINVAL' and
do nothing.

   A shared global variable X can be protected by a mutex as follows:

     int x;
     pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

   All accesses and modifications to X should be bracketed by calls to
`pthread_mutex_lock' and `pthread_mutex_unlock' as follows:

     pthread_mutex_lock(&mut);
     /* operate on x */
     pthread_mutex_unlock(&mut);

   Mutex attributes can be specified at mutex creation time, by passing
a mutex attribute object as second argument to `pthread_mutex_init'.
Passing `NULL' is equivalent to passing a mutex attribute object with
all attributes set to their default values.

 - Function: int pthread_mutexattr_init (pthread_mutexattr_t *ATTR)
     `pthread_mutexattr_init' initializes the mutex attribute object
     ATTR and fills it with default values for the attributes.

     This function always returns 0.

 - Function: int pthread_mutexattr_destroy (pthread_mutexattr_t *ATTR)
     `pthread_mutexattr_destroy' destroys a mutex attribute object,
     which must not be reused until it is reinitialized.
     `pthread_mutexattr_destroy' does nothing in the LinuxThreads
     implementation.

     This function always returns 0.

   LinuxThreads supports only one mutex attribute: the mutex type,
which is either `PTHREAD_MUTEX_ADAPTIVE_NP' for "fast" mutexes,
`PTHREAD_MUTEX_RECURSIVE_NP' for "recursive" mutexes,
`PTHREAD_MUTEX_TIMED_NP' for "timed" mutexes, or
`PTHREAD_MUTEX_ERRORCHECK_NP' for "error checking" mutexes.  As the
`NP' suffix indicates, this is a non-portable extension to the POSIX
standard and should not be employed in portable programs.

   The mutex type determines what happens if a thread attempts to lock a
mutex it already owns with `pthread_mutex_lock'. If the mutex is of the
"fast" type, `pthread_mutex_lock' simply suspends the calling thread
forever.  If the mutex is of the "error checking" type,
`pthread_mutex_lock' returns immediately with the error code `EDEADLK'.
If the mutex is of the "recursive" type, the call to
`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
`pthread_mutex_unlock' the same number of times before the mutex
returns to the unlocked state.

   The default mutex type is "timed", that is, `PTHREAD_MUTEX_TIMED_NP'.

 - Function: int pthread_mutexattr_settype (pthread_mutexattr_t *ATTR,
          int TYPE)
     `pthread_mutexattr_settype' sets the mutex type attribute in ATTR
     to the value specified by TYPE.

     If TYPE is not `PTHREAD_MUTEX_ADAPTIVE_NP',
     `PTHREAD_MUTEX_RECURSIVE_NP', `PTHREAD_MUTEX_TIMED_NP', or
     `PTHREAD_MUTEX_ERRORCHECK_NP', this function will return `EINVAL'
     and leave ATTR unchanged.

     The standard Unix98 identifiers `PTHREAD_MUTEX_DEFAULT',
     `PTHREAD_MUTEX_NORMAL', `PTHREAD_MUTEX_RECURSIVE', and
     `PTHREAD_MUTEX_ERRORCHECK' are also permitted.


 - Function: int pthread_mutexattr_gettype (const pthread_mutexattr_t
          *ATTR, int *TYPE)
     `pthread_mutexattr_gettype' retrieves the current value of the
     mutex type attribute in ATTR and stores it in the location pointed
     to by TYPE.

     This function always returns 0.

