   This file documents the GNU C library.

   This is Edition 0.06 DRAFT, last updated 24 October 1994, of `The
GNU C Library Reference Manual', for Version 1.09 Beta.

   Copyright (C) 1993, 1994 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 translations of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.

Waiting for Input or Output
===========================

   Sometimes a program needs to accept input on multiple input channels
whenever input arrives.  For example, some workstations may have devices
such as a digitizing tablet, function button box, or dial box that are
connected via normal asynchronous serial interfaces; good user interface
style requires responding immediately to input on any device.  Another
example is a program that acts as a server to several other processes
via pipes or sockets.

   You cannot normally use `read' for this purpose, because this blocks
the program until input is available on one particular file descriptor;
input on other channels won't wake it up.  You could set nonblocking
mode and poll each file descriptor in turn, but this is very
inefficient.

   A better solution is to use the `select' function.  This blocks the
program until input or output is ready on a specified set of file
descriptors, or until a timer expires, whichever comes first.  This
facility is declared in the header file `sys/types.h'.

   In the case of a server socket (see Listening.), we say that
"input" is available when there are pending connections that could be
accepted (see Accepting Connections.).  `accept' for server sockets
blocks and interacts with `select' just as `read' does for normal input.

   The file descriptor sets for the `select' function are specified as
`fd_set' objects.  Here is the description of the data type and some
macros for manipulating these objects.

 - Data Type: fd_set
     The `fd_set' data type represents file descriptor sets for the
     `select' function.  It is actually a bit array.

 - Macro: int FD_SETSIZE
     The value of this macro is the maximum number of file descriptors
     that a `fd_set' object can hold information about.  On systems
     with a fixed maximum number, `FD_SETSIZE' is at least that number.
     On some systems, including GNU, there is no absolute limit on the
     number of descriptors open, but this macro still has a constant
     value which controls the number of bits in an `fd_set'.

 - Macro: void FD_ZERO (fd_set *SET)
     This macro initializes the file descriptor set SET to be the empty
     set.

 - Macro: void FD_SET (int FILEDES, fd_set *SET)
     This macro adds FILEDES to the file descriptor set SET.

 - Macro: void FD_CLR (int FILEDES, fd_set *SET)
     This macro removes FILEDES from the file descriptor set SET.

 - Macro: int FD_ISSET (int FILEDES, fd_set *SET)
     This macro returns a nonzero value (true) if FILEDES is a member
     of the the file descriptor set SET, and zero (false) otherwise.

   Next, here is the description of the `select' function itself.

 - Function: int select (int NFDS, fd_set *READ-FDS, fd_set *WRITE-FDS,
          fd_set *EXCEPT-FDS, struct timeval *TIMEOUT)
     The `select' function blocks the calling process until there is
     activity on any of the specified sets of file descriptors, or
     until the timeout period has expired.

     The file descriptors specified by the READ-FDS argument are
     checked to see if they are ready for reading (or if a server
     socket, for accepting a connection); the WRITE-FDS file
     descriptors are checked to see if they are ready for writing; and
     the EXCEPT-FDS file descriptors are checked for exceptional
     conditions.  You can pass a null pointer for any of these
     arguments if you are not interested in checking for that kind of
     condition.  "Exceptional conditions" does not mean errors--errors
     are reported immediately when an erroneous system call is
     executed, and do not constitute a state of the descriptor.
     Rather, they include conditions such as the presence of an urgent
     message on a socket.  (see Sockets, for information on urgent
     messages.)

     The `select' function checks only the first NFDS file descriptors.
     The usual thing is to pass `FD_SETSIZE' as the value of this
     argument.

     The TIMEOUT specifies the maximum time to wait.  If you pass a
     null pointer for this argument, it means to block indefinitely
     until one of the file descriptors is ready.  Otherwise, you should
     provide the time in `struct timeval' format; see
     High-Resolution Calendar.  Specify zero as the time (a `struct
     timeval' containing all zeros) if you want to find out which
     descriptors are ready without waiting if none are ready.

     The normal return value from `select' is the total number of ready
     file descriptors in all of the sets.  Each of the argument sets is
     overwritten with information about the descriptors that are ready
     for the corresponding operation.  Thus, to see if a particular
     descriptor DESC has input, use `FD_ISSET (DESC, READ-FDS)' after
     `select' returns.

     If `select' returns because the timeout period expires, it returns
     a value of zero.

     Any signal will cause `select' to return immediately.  So if your
     program uses signals, you can't rely on `select' to keep waiting
     for the full time specified.  If you want to be sure of waiting
     for a particular amount of time, you must check for `EINTR' and
     repeat the `select' with a newly calculated timeout based on the
     current time.  See the example below.  See also Interrupted Primitives.

     If an error occurs, `select' returns `-1' and does not modify the
     argument file descriptor sets.  The following `errno' error
     conditions are defined for this function:

    `EBADF'
          One of the file descriptor sets specified an invalid file
          descriptor.

    `EINTR'
          The operation was interrupted by a signal.  See Interrupted Primitives.

    `EINVAL'
          The TIMEOUT argument is invalid; one of the components is
          negative or too large.

   *Portability Note:*  The `select' function is a BSD Unix feature.

   Here is an example showing how you can use `select' to establish a
timeout period for reading from a file descriptor.  The `input_timeout'
function blocks the calling process until input is available on the
file descriptor, or until the timeout period expires.

     #include <stdio.h>
     #include <unistd.h>
     #include <sys/types.h>
     #include <sys/time.h>

     int
     input_timeout (int filedes, unsigned int seconds)
     {
       fd_set set;
       struct timeval timeout;

       /* Initialize the file descriptor set. */
       FD_ZERO (&set);
       FD_SET (filedes, &set);

       /* Initialize the timeout data structure. */
       timeout.tv_sec = seconds;
       timeout.tv_usec = 0;

       /* `select' returns 0 if timeout, 1 if input available, -1 if error. */
       return TEMP_FAILURE_RETRY (select (FD_SETSIZE,
                                          &set, NULL, NULL,
                                          &timeout));
     }

     int
     main (void)
     {
       fprintf (stderr, "select returned %d.\n",
                input_timeout (STDIN_FILENO, 5));
       return 0;
     }

   There is another example showing the use of `select' to multiplex
input from multiple sockets in Server Example.

Control Operations on Files
===========================

   This section describes how you can perform various other operations
on file descriptors, such as inquiring about or setting flags describing
the status of the file descriptor, manipulating record locks, and the
like.  All of these operations are performed by the function `fcntl'.

   The second argument to the `fcntl' function is a command that
specifies which operation to perform.  The function and macros that name
various flags that are used with it are declared in the header file
`fcntl.h'.  (Many of these flags are also used by the `open' function;
see Opening and Closing Files.)

 - Function: int fcntl (int FILEDES, int COMMAND, ...)
     The `fcntl' function performs the operation specified by COMMAND
     on the file descriptor FILEDES.  Some commands require additional
     arguments to be supplied.  These additional arguments and the
     return value and error conditions are given in the detailed
     descriptions of the individual commands.

     Briefly, here is a list of what the various commands are.

    `F_DUPFD'
          Duplicate the file descriptor (return another file descriptor
          pointing to the same open file).  See Duplicating Descriptors.

    `F_GETFD'
          Get flags associated with the file descriptor.  See
          Descriptor Flags.

    `F_SETFD'
          Set flags associated with the file descriptor.  See
          Descriptor Flags.

    `F_GETFL'
          Get flags associated with the open file.  See File Status Flags.

    `F_SETFL'
          Set flags associated with the open file.  See File Status Flags.

    `F_GETLK'
          Get a file lock.  See File Locks.

    `F_SETLK'
          Set or clear a file lock.  See File Locks.

    `F_SETLKW'
          Like `F_SETLK', but wait for completion.  See File Locks.

    `F_GETOWN'
          Get process or process group ID to receive `SIGIO' signals.
          See Interrupt Input.

    `F_SETOWN'
          Set process or process group ID to receive `SIGIO' signals.
          See Interrupt Input.

Duplicating Descriptors
=======================

   You can "duplicate" a file descriptor, or allocate another file
descriptor that refers to the same open file as the original.  Duplicate
descriptors share one file position and one set of file status flags
(see File Status Flags.), but each has its own set of file
descriptor flags (see Descriptor Flags.).

   The major use of duplicating a file descriptor is to implement
"redirection" of input or output:  that is, to change the file or pipe
that a particular file descriptor corresponds to.

   You can perform this operation using the `fcntl' function with the
`F_DUPFD' command, but there are also convenient functions `dup' and
`dup2' for duplicating descriptors.

   The `fcntl' function and flags are declared in `fcntl.h', while
prototypes for `dup' and `dup2' are in the header file `unistd.h'.

 - Function: int dup (int OLD)
     This function copies descriptor OLD to the first available
     descriptor number (the first number not currently open).  It is
     equivalent to `fcntl (OLD, F_DUPFD, 0)'.

 - Function: int dup2 (int OLD, int NEW)
     This function copies the descriptor OLD to descriptor number NEW.

     If OLD is an invalid descriptor, then `dup2' does nothing; it does
     not close NEW.  Otherwise, the new duplicate of OLD replaces any
     previous meaning of descriptor NEW, as if NEW were closed first.

     If OLD and NEW are different numbers, and OLD is a valid
     descriptor number, then `dup2' is equivalent to:

          close (NEW);
          fcntl (OLD, F_DUPFD, NEW)

     However, `dup2' does this atomically; there is no instant in the
     middle of calling `dup2' at which NEW is closed and not yet a
     duplicate of OLD.

 - Macro: int F_DUPFD
     This macro is used as the COMMAND argument to `fcntl', to copy the
     file descriptor given as the first argument.

     The form of the call in this case is:

          fcntl (OLD, F_DUPFD, NEXT-FILEDES)

     The NEXT-FILEDES argument is of type `int' and specifies that the
     file descriptor returned should be the next available one greater
     than or equal to this value.

     The return value from `fcntl' with this command is normally the
     value of the new file descriptor.  A return value of `-1'
     indicates an error.  The following `errno' error conditions are
     defined for this command:

    `EBADF'
          The OLD argument is invalid.

    `EINVAL'
          The NEXT-FILEDES argument is invalid.

    `EMFILE'
          There are no more file descriptors available--your program is
          already using the maximum.  In BSD and GNU, the maximum is
          controlled by a resource limit that can be changed; see
          Limits on Resources., for more information about the
          `RLIMIT_NOFILE' limit.

     `ENFILE' is not a possible error code for `dup2' because `dup2'
     does not create a new opening of a file; duplicate descriptors do
     not count toward the limit which `ENFILE' indicates.  `EMFILE' is
     possible because it refers to the limit on distinct descriptor
     numbers in use in one process.

   Here is an example showing how to use `dup2' to do redirection.
Typically, redirection of the standard streams (like `stdin') is done
by a shell or shell-like program before calling one of the `exec'
functions (see Executing a File.) to execute a new program in a
child process.  When the new program is executed, it creates and
initializes the standard streams to point to the corresponding file
descriptors, before its `main' function is invoked.

   So, to redirect standard input to a file, the shell could do
something like:

     pid = fork ();
     if (pid == 0)
       {
         char *filename;
         char *program;
         int file;
         ...
         file = TEMP_FAILURE_RETRY (open (filename, O_RDONLY));
         dup2 (file, STDIN_FILENO);
         TEMP_FAILURE_RETRY (close (file));
         execv (program, NULL);
       }

   There is also a more detailed example showing how to implement
redirection in the context of a pipeline of processes in
Launching Jobs.

File Descriptor Flags
=====================

   "File descriptor flags" are miscellaneous attributes of a file
descriptor.  These flags are associated with particular file
descriptors, so that if you have created duplicate file descriptors
from a single opening of a file, each descriptor has its own set of
flags.

   Currently there is just one file descriptor flag: `FD_CLOEXEC',
which causes the descriptor to be closed if you use any of the
`exec...' functions (see Executing a File.).

   The symbols in this section are defined in the header file `fcntl.h'.

 - Macro: int F_GETFD
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should return the file descriptor flags associated with
     the FILEDES argument.

     The normal return value from `fcntl' with this command is a
     nonnegative number which can be interpreted as the bitwise OR of
     the individual flags (except that currently there is only one flag
     to use).

     In case of an error, `fcntl' returns `-1'.  The following `errno'
     error conditions are defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

 - Macro: int F_SETFD
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set the file descriptor flags associated with the
     FILEDES argument.  This requires a third `int' argument to specify
     the new flags, so the form of the call is:

          fcntl (FILEDES, F_SETFD, NEW-FLAGS)

     The normal return value from `fcntl' with this command is an
     unspecified value other than `-1', which indicates an error.  The
     flags and error conditions are the same as for the `F_GETFD'
     command.

   The following macro is defined for use as a file descriptor flag with
the `fcntl' function.  The value is an integer constant usable as a bit
mask value.

 - Macro: int FD_CLOEXEC
     This flag specifies that the file descriptor should be closed when
     an `exec' function is invoked; see Executing a File.  When
     a file descriptor is allocated (as with `open' or `dup'), this bit
     is initially cleared on the new file descriptor, meaning that
     descriptor will survive into the new program after `exec'.

   If you want to modify the file descriptor flags, you should get the
current flags with `F_GETFD' and modify the value.  Don't assume that
the flags listed here are the only ones that are implemented; your
program may be run years from now and more flags may exist then.  For
example, here is a function to set or clear the flag `FD_CLOEXEC'
without altering any other flags:

     /* Set the `FD_CLOEXEC' flag of DESC if VALUE is nonzero,
        or clear the flag if VALUE is 0.
        Return 0 on success, or -1 on error with `errno' set. */

     int
     set_cloexec_flag (int desc, int value)
     {
       int oldflags = fcntl (desc, F_GETFD, 0);
       /* If reading the flags failed, return error indication now.
       if (oldflags < 0)
         return oldflags;
       /* Set just the flag we want to set. */
       if (value != 0)
         oldflags |= FD_CLOEXEC;
       else
         oldflags &= ~FD_CLOEXEC;
       /* Store modified flag word in the descriptor. */
       return fcntl (desc, F_SETFD, oldflags);
     }

File Status Flags
=================

   "File status flags" are used to specify attributes of the opening of
a file.  Unlike the file descriptor flags discussed in Descriptor Flags,
the file status flags are shared by duplicated file descriptors
resulting from a single opening of the file.  The file status flags are
specified with the FLAGS argument to `open'; see Opening and Closing Files..

   File status flags fall into three categories, which are described in
the following sections.

   * See Access Modes, specify what type of access is allowed to the
     file: reading, writing, or both.  They are set by `open' and are
     returned by `fcntl', but cannot be changed.

   * See Open-time Flags, control details of what `open' will do.
     These flags are not preserved after the `open' call.

   * See Operating Modes, affect how operations such as `read' and
     `write' are done.  They are set by `open', and can be fetched or
     changed with `fcntl'.

   The symbols in this section are defined in the header file `fcntl.h'.

File Access Modes
-----------------

   The file access modes allow a file descriptor to be used for reading,
writing, or both.  (In the GNU system, they can also allow none of
these, and allow execution of the file as a program.)  The access modes
are chosen when the file is opened, and never change.

 - Macro: int O_RDONLY
     Open the file for read access.

 - Macro: int O_WRONLY
     Open the file for write access.

 - Macro: int O_RDWR
     Open the file for both reading and writing.

   In the GNU system (and not in other systems), `O_RDONLY' and
`O_WRONLY' are independent bits that can be bitwise-ORed together, and
it is valid for either bit to be set or clear.  This means that
`O_RDWR' is the same as `O_RDONLY|O_WRONLY'.  A file access mode of
zero is permissible; it allows no operations that do input or output to
the file, but does allow other operations such as `fchmod'.  On the GNU
system, since "read-only" or "write-only" is a misnomer, `fcntl.h'
defines additional names for the file access modes.  These names are
preferred when writing GNU-specific code.  But most programs will want
to be portable to other POSIX.1 systems and should use the POSIX.1
names above instead.

 - Macro: int O_READ
     Open the file for reading.  Same as `O_RDWR'; only defined on GNU.

 - Macro: int O_WRITE
     Open the file for reading.  Same as `O_WRONLY'; only defined on
     GNU.

 - Macro: int O_EXEC
     Open the file for executing.  Only defined on GNU.

   To determine the file access mode with `fcntl', you must extract the
access mode bits from the retrieved file status flags.  In the GNU
system, you can just test the `O_READ' and `O_WRITE' bits in the flags
word.  But in other POSIX.1 systems, reading and writing access modes
are not stored as distinct bit flags.  The portable way to extract the
file access mode bits is with `O_ACCMODE'.

 - Macro: int O_ACCMODE
     This macro stands for a mask that can be bitwise-ANDed with the
     file status flag value to produce a value representing the file
     access mode.  The mode will be `O_RDONLY', `O_WRONLY', or `O_RDWR'.
     (In the GNU system it could also be zero.)

Open-time Flags
---------------

   The open-time flags specify options affecting how `open' will behave.
These options are not preserved once the file is open.  The exception to
this is `O_NONBLOCK', which is also an I/O operating mode and so it
*is* saved.  See Opening and Closing Files, for how to call `open'.

   There are two sorts of options specified by open-time flags.

   * "File name translation flags" affect how `open' looks up the file
     name to locate the file, and whether the file can be created.

   * "Open-time action flags" specify extra operations that `open' will
     perform on the file once it is open.

   Here are the file name translation flags.

 - Macro: int O_CREAT
     If set, the file will be created if it doesn't already exist.

 - Macro: int O_EXCL
     If both `O_CREAT' and `O_EXCL' are set, then `open' fails if the
     specified file already exists.  This is guaranteed to never
     clobber an existing file.

 - Macro: int O_NONBLOCK
     This prevents `open' from blocking for a "long time" to open the
     file.  This is only meaningful for some kinds of files, usually
     devices such as serial ports.  Often opening a port to a modem
     blocks until the modem reports carrier detection; if `O_NONBLOCK'
     is specified, `open' will return immediately without a carrier.

     Note that the `O_NONBLOCK' flag is overloaded as both an I/O
     operating mode and a file name translation flag.  This means that
     specifying `O_NONBLOCK' in `open' also sets nonblocking I/O mode;
     see Operating Modes..  To open the file without blocking but
     do normal I/O that blocks, you must call `open' with `O_NONBLOCK'
     set and then call `fcntl' to turn the bit off.

 - Macro: int O_NOCTTY
     If the named file is a terminal device, don't make it the
     controlling terminal for the process.  See Job Control, for
     information about what it means to be the controlling terminal.
     In the GNU system and 4.4 BSD, opening a file never makes it the
     controlling terminal and `O_NOCTTY' is zero.

   These three file name translation flags exist only in the GNU system.

 - Macro: int O_IGNORE_CTTY
     Do not recognize the named file as the controlling terminal, even
     if it refers to the process's existing controlling terminal
     device.  Operations on the new file descriptor will never induce
     job control signals.  See Job Control.

 - Macro: int O_NOLINK
     If the named file is a symbolic link, open the link itself instead
     of the file it refers to.  (`fstat' on the new file descriptor will
     return the information returned by `lstat' on the link's name.)

 - Macro: int O_NOTRANS
     If the named file is specially translated, do not invoke the
     translator.  Open the bare file the translator itself sees.

   The open-time action flags tell `open' to do additional operations
which are not really related to opening the file.  The reason to do them
as part of `open' instead of in separate calls is that `open' can do
them atomically.

 - Macro: int O_TRUNC
     Truncate the file to zero length.  This option is only useful for
     regular files, not special files such as directories or FIFOs.
     POSIX.1 requires that you open the file for writing to use
     `O_TRUNC'.  In BSD and GNU you must have permission to write the
     file to truncate it, but you need not open for write access.

     This is the only open-time action flag specified by POSIX.1.
     There is no good reason for truncation to be done by `open',
     instead of by calling `ftruncate' afterwards.  The `O_TRUNC' flag
     existed in Unix before `ftruncate' was invented, and is retained
     for backward compatibility.

 - Macro: int O_SHLOCK
     Acquire a shared lock on the file, as with `flock'.  See File Locks.

     If `O_CREAT' is specified, the locking is done atomically when
     creating the file.  You are guaranteed that no other process will
     get the lock on the new file first.

 - Macro: int O_EXLOCK
     Acquire an exclusive lock on the file, as with `flock'.  See
     File Locks.  This is atomic like `O_SHLOCK'.

I/O Operating Modes
-------------------

   The operating modes affect how input and output operations using a
file descriptor work.  These flags are set by `open' and can be fetched
and changed with `fcntl'.

 - Macro: int O_APPEND
     The bit that enables append mode for the file.  If set, then all
     `write' operations write the data at the end of the file, extending
     it, regardless of the current file position.

 - O_NONBLOCK:
     The bit that enables nonblocking mode for the file.  If this bit
     is set, `read' requests on the file can return immediately with a
     failure status if there is no input immediately available, instead
     of blocking.  Likewise, `write' requests can also return
     immediately with a failure status if the output can't be written
     immediately.

     Note that the `O_NONBLOCK' flag is overloaded as both an I/O
     operating mode and a file name translation flag; see Open-time Flags..

 - Macro: int O_NDELAY
     This is an obsolete name for `O_NONBLOCK', provided for
     compatibility with BSD.  It is not defined by the POSIX.1 standard.

   The remaining operating modes are BSD and GNU extensions.  They
exist only on some systems.  On other systems, these macros are not
defined.

 - Macro: int O_ASYNC
     The bit that enables asynchronous input mode.  If set, then `SIGIO'
     signals will be generated when input is available.  See
     Interrupt Input.

     Asynchronous input mode is a BSD feature.

 - Macro: int O_FSYNC
     The bit that enables synchronous writing for the file.  If set,
     each `write' call will make sure the data is reliably stored on
     disk before returning.  Synchronous writing is a BSD feature.

 - Macro: int O_SYNC
     This is another name for `O_FSYNC'.  They have the same value.

 - Macro: int O_NOATIME
     If this bit is set, `read' will not update the access time of the
     file.  See File Times.  This is used by programs that do
     backups, so that backing a file up does not count as reading it.

     This is a GNU extension.

Getting and Setting File Status Flags
-------------------------------------

   The `fcntl' function can fetch or change file status flags.

 - Macro: int F_GETFL
     This macro is used as the COMMAND argument to `fcntl', to read the
     file status flags for the open file with descriptor FILEDES.

     The normal return value from `fcntl' with this command is a
     nonnegative number which can be interpreted as the bitwise OR of
     the individual flags.  Since the file access modes are not
     single-bit values, you can mask off other bits in the returned
     flags with `O_ACCMODE' to compare them.

     In case of an error, `fcntl' returns `-1'.  The following `errno'
     error conditions are defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

 - Macro: int F_SETFL
     This macro is used as the COMMAND argument to `fcntl', to set the
     file status flags for the open file corresponding to the FILEDES
     argument.  This command requires a third `int' argument to specify
     the new flags, so the call looks like this:

          fcntl (FILEDES, F_SETFL, NEW-FLAGS)

     You can't change the access mode for the file in this way; that is,
     whether the file descriptor was opened for reading or writing.

     The normal return value from `fcntl' with this command is an
     unspecified value other than `-1', which indicates an error.  The
     error conditions are the same as for the `F_GETFL' command.

   If you want to modify the file status flags, you should get the
current flags with `F_GETFL' and modify the value.  Don't assume that
the flags listed here are the only ones that are implemented; your
program may be run years from now and more flags may exist then.  For
example, here is a function to set or clear the flag `O_NONBLOCK'
without altering any other flags:

     /* Set the `O_NONBLOCK' flag of DESC if VALUE is nonzero,
        or clear the flag if VALUE is 0.
        Return 0 on success, or -1 on error with `errno' set. */

     int
     set_nonblock_flag (int desc, int value)
     {
       int oldflags = fcntl (desc, F_GETFL, 0);
       /* If reading the flags failed, return error indication now. */
       if (oldflags == -1)
         return -1;
       /* Set just the flag we want to set. */
       if (value != 0)
         oldflags |= O_NONBLOCK;
       else
         oldflags &= ~O_NONBLOCK;
       /* Store modified flag word in the descriptor. */
       return fcntl (desc, F_SETFL, oldflags);
     }

File Locks
==========

   The remaining `fcntl' commands are used to support "record locking",
which permits multiple cooperating programs to prevent each other from
simultaneously accessing parts of a file in error-prone ways.

   An "exclusive" or "write" lock gives a process exclusive access for
writing to the specified part of the file.  While a write lock is in
place, no other process can lock that part of the file.

   A "shared" or "read" lock prohibits any other process from
requesting a write lock on the specified part of the file.  However,
other processes can request read locks.

   The `read' and `write' functions do not actually check to see
whether there are any locks in place.  If you want to implement a
locking protocol for a file shared by multiple processes, your
application must do explicit `fcntl' calls to request and clear locks
at the appropriate points.

   Locks are associated with processes.  A process can only have one
kind of lock set for each byte of a given file.  When any file
descriptor for that file is closed by the process, all of the locks
that process holds on that file are released, even if the locks were
made using other descriptors that remain open.  Likewise, locks are
released when a process exits, and are not inherited by child processes
created using `fork' (see Creating a Process.).

   When making a lock, use a `struct flock' to specify what kind of
lock and where.  This data type and the associated macros for the
`fcntl' function are declared in the header file `fcntl.h'.

 - Data Type: struct flock
     This structure is used with the `fcntl' function to describe a file
     lock.  It has these members:

    `short int l_type'
          Specifies the type of the lock; one of `F_RDLCK', `F_WRLCK',
          or `F_UNLCK'.

    `short int l_whence'
          This corresponds to the WHENCE argument to `fseek' or
          `lseek', and specifies what the offset is relative to.  Its
          value can be one of `SEEK_SET', `SEEK_CUR', or `SEEK_END'.

    `off_t l_start'
          This specifies the offset of the start of the region to which
          the lock applies, and is given in bytes relative to the point
          specified by `l_whence' member.

    `off_t l_len'
          This specifies the length of the region to be locked.  A
          value of `0' is treated specially; it means the region
          extends to the end of the file.

    `pid_t l_pid'
          This field is the process ID (see Process Creation Concepts.)
          of the process holding the lock.  It is filled
          in by calling `fcntl' with the `F_GETLK' command, but is
          ignored when making a lock.

 - Macro: int F_GETLK
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should get information about a lock.  This command
     requires a third argument of type `struct flock *' to be passed to
     `fcntl', so that the form of the call is:

          fcntl (FILEDES, F_GETLK, LOCKP)

     If there is a lock already in place that would block the lock
     described by the LOCKP argument, information about that lock
     overwrites `*LOCKP'.  Existing locks are not reported if they are
     compatible with making a new lock as specified.  Thus, you should
     specify a lock type of `F_WRLCK' if you want to find out about both
     read and write locks, or `F_RDLCK' if you want to find out about
     write locks only.

     There might be more than one lock affecting the region specified
     by the LOCKP argument, but `fcntl' only returns information about
     one of them.  The `l_whence' member of the LOCKP structure is set
     to `SEEK_SET' and the `l_start' and `l_len' fields set to identify
     the locked region.

     If no lock applies, the only change to the LOCKP structure is to
     update the `l_type' to a value of `F_UNLCK'.

     The normal return value from `fcntl' with this command is an
     unspecified value other than `-1', which is reserved to indicate an
     error.  The following `errno' error conditions are defined for
     this command:

    `EBADF'
          The FILEDES argument is invalid.

    `EINVAL'
          Either the LOCKP argument doesn't specify valid lock
          information, or the file associated with FILEDES doesn't
          support locks.

 - Macro: int F_SETLK
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set or clear a lock.  This command requires a third
     argument of type `struct flock *' to be passed to `fcntl', so that
     the form of the call is:

          fcntl (FILEDES, F_SETLK, LOCKP)

     If the process already has a lock on any part of the region, the
     old lock on that part is replaced with the new lock.  You can
     remove a lock by specifying a lock type of `F_UNLCK'.

     If the lock cannot be set, `fcntl' returns immediately with a value
     of `-1'.  This function does not block waiting for other processes
     to release locks.  If `fcntl' succeeds, it return a value other
     than `-1'.

     The following `errno' error conditions are defined for this
     function:

    `EACCES'
    `EAGAIN'
          The lock cannot be set because it is blocked by an existing
          lock on the file.  Some systems use `EAGAIN' in this case,
          and other systems use `EACCES'; your program should treat
          them alike, after `F_SETLK'.

    `EBADF'
          Either: the FILEDES argument is invalid; you requested a read
          lock but the FILEDES is not open for read access; or, you
          requested a write lock but the FILEDES is not open for write
          access.

    `EINVAL'
          Either the LOCKP argument doesn't specify valid lock
          information, or the file associated with FILEDES doesn't
          support locks.

    `ENOLCK'
          The system has run out of file lock resources; there are
          already too many file locks in place.

          Well-designed file systems never report this error, because
          they have no limitation on the number of locks.  However, you
          must still take account of the possibility of this error, as
          it could result from network access to a file system on
          another machine.

    `EDEADLK'
          The specified region is being locked by another process.  But
          that process is waiting to lock a region which the current
          process has locked, so waiting for the lock would result in
          deadlock.  The system does not guarantee that it will detect
          all such conditions, but it lets you know if it notices one.

 - Macro: int F_SETLKW
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set or clear a lock.  It is just like the `F_SETLK'
     command, but causes the process to block (or wait) until the
     request can be specified.

     This command requires a third argument of type `struct flock *', as
     for the `F_SETLK' command.

     The `fcntl' return values and errors are the same as for the
     `F_SETLK' command, but these additional `errno' error conditions
     are defined for this command:

    `EINTR'
          The function was interrupted by a signal while it was waiting.
          See Interrupted Primitives.

    `EDEADLK'
          A deadlock condition was detected.  This can happen if two
          processes each already controlling a locked region request a
          lock on the same region locked by the other process.

   The following macros are defined for use as values for the `l_type'
member of the `flock' structure.  The values are integer constants.

`F_RDLCK'
     This macro is used to specify a read (or shared) lock.

`F_WRLCK'
     This macro is used to specify a write (or exclusive) lock.

`F_UNLCK'
     This macro is used to specify that the region is unlocked.

   As an example of a situation where file locking is useful, consider a
program that can be run simultaneously by several different users, that
logs status information to a common file.  One example of such a program
might be a game that uses a file to keep track of high scores.  Another
example might be a program that records usage or accounting information
for billing purposes.

   Having multiple copies of the program simultaneously writing to the
file could cause the contents of the file to become mixed up.  But you
can prevent this kind of problem by setting a write lock on the file
before actually writing to the file.

   If the program also needs to read the file and wants to make sure
that the contents of the file are in a consistent state, then it can
also use a read lock.  While the read lock is set, no other process can
lock that part of the file for writing.

   Remember that file locks are only a *voluntary* protocol for
controlling access to a file.  There is still potential for access to
the file by programs that don't use the lock protocol.

Interrupt-Driven Input
======================

   If you set the `O_ASYNC' status flag on a file descriptor (see
File Status Flags.), a `SIGIO' signal is sent whenever input or
output becomes possible on that file descriptor.  The process or
process group to receive the signal can be selected by using the
`F_SETOWN' command to the `fcntl' function.  If the file descriptor is
a socket, this also selects the recipient of `SIGURG' signals that are
delivered when out-of-band data arrives on that socket; see
Out-of-Band Data.  (`SIGURG' is sent in any situation where `select'
would report the socket as having an "exceptional condition".  See
Waiting for I/O.)

   If the file descriptor corresponds to a terminal device, then `SIGIO'
signals are sent to the foreground process group of the terminal.
See Job Control.

   The symbols in this section are defined in the header file `fcntl.h'.

 - Macro: int F_GETOWN
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should get information about the process or process group
     to which `SIGIO' signals are sent.  (For a terminal, this is
     actually the foreground process group ID, which you can get using
     `tcgetpgrp'; see Terminal Access Functions.)

     The return value is interpreted as a process ID; if negative, its
     absolute value is the process group ID.

     The following `errno' error condition is defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

 - Macro: int F_SETOWN
     This macro is used as the COMMAND argument to `fcntl', to specify
     that it should set the process or process group to which `SIGIO'
     signals are sent.  This command requires a third argument of type
     `pid_t' to be passed to `fcntl', so that the form of the call is:

          fcntl (FILEDES, F_SETOWN, PID)

     The PID argument should be a process ID.  You can also pass a
     negative number whose absolute value is a process group ID.

     The return value from `fcntl' with this command is `-1' in case of
     error and some other value if successful.  The following `errno'
     error conditions are defined for this command:

    `EBADF'
          The FILEDES argument is invalid.

    `ESRCH'
          There is no process or process group corresponding to PID.

File System Interface
*********************

   This chapter describes the GNU C library's functions for manipulating
files.  Unlike the input and output functions described in I/O on Streams
and Low-Level I/O, these functions are concerned with
operating on the files themselves, rather than on their contents.

   Among the facilities described in this chapter are functions for
examining or modifying directories, functions for renaming and deleting
files, and functions for examining and setting file attributes such as
access permissions and modification times.

Working Directory
=================

   Each process has associated with it a directory, called its "current
working directory" or simply "working directory", that is used in the
resolution of relative file names (see File Name Resolution.).

   When you log in and begin a new session, your working directory is
initially set to the home directory associated with your login account
in the system user database.  You can find any user's home directory
using the `getpwuid' or `getpwnam' functions; see User Database.

   Users can change the working directory using shell commands like
`cd'.  The functions described in this section are the primitives used
by those commands and by other programs for examining and changing the
working directory.

   Prototypes for these functions are declared in the header file
`unistd.h'.

 - Function: char * getcwd (char *BUFFER, size_t SIZE)
     The `getcwd' function returns an absolute file name representing
     the current working directory, storing it in the character array
     BUFFER that you provide.  The SIZE argument is how you tell the
     system the allocation size of BUFFER.

     The GNU library version of this function also permits you to
     specify a null pointer for the BUFFER argument.  Then `getcwd'
     allocates a buffer automatically, as with `malloc' (see
     Unconstrained Allocation.).  If the SIZE is greater than zero,
     then the buffer is that large; otherwise, the buffer is as large
     as necessary to hold the result.

     The return value is BUFFER on success and a null pointer on
     failure.  The following `errno' error conditions are defined for
     this function:

    `EINVAL'
          The SIZE argument is zero and BUFFER is not a null pointer.

    `ERANGE'
          The SIZE argument is less than the length of the working
          directory name.  You need to allocate a bigger array and try
          again.

    `EACCES'
          Permission to read or search a component of the file name was
          denied.

   Here is an example showing how you could implement the behavior of
GNU's `getcwd (NULL, 0)' using only the standard behavior of `getcwd':

     char *
     gnu_getcwd ()
     {
       int size = 100;
       char *buffer = (char *) xmalloc (size);

       while (1)
         {
           char *value = getcwd (buffer, size);
           if (value != 0)
             return buffer;
           size *= 2;
           free (buffer);
           buffer = (char *) xmalloc (size);
         }
     }

See Malloc Examples, for information about `xmalloc', which is not
a library function but is a customary name used in most GNU software.

 - Function: char * getwd (char *BUFFER)
     This is similar to `getcwd', but has no way to specify the size of
     the buffer.  The GNU library provides `getwd' only for backwards
     compatibility with BSD.

     The BUFFER argument should be a pointer to an array at least
     `PATH_MAX' bytes long (see Limits for Files.).  In the GNU
     system there is no limit to the size of a file name, so this is not
     necessarily enough space to contain the directory name.  That is
     why this function is deprecated.

 - Function: int chdir (const char *FILENAME)
     This function is used to set the process's working directory to
     FILENAME.

     The normal, successful return value from `chdir' is `0'.  A value
     of `-1' is returned to indicate an error.  The `errno' error
     conditions defined for this function are the usual file name
     syntax errors (see File Name Errors.), plus `ENOTDIR' if the
     file FILENAME is not a directory.

Accessing Directories
=====================

   The facilities described in this section let you read the contents
of a directory file.  This is useful if you want your program to list
all the files in a directory, perhaps as part of a menu.

   The `opendir' function opens a "directory stream" whose elements are
directory entries.  You use the `readdir' function on the directory
stream to retrieve these entries, represented as `struct dirent'
objects.  The name of the file for each entry is stored in the `d_name'
member of this structure.  There are obvious parallels here to the
stream facilities for ordinary files, described in I/O on Streams.