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.10, last updated 2001-07-06, of `The GNU C Library
Reference Manual', for Version 2.2.x.

   Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002
Free Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software Needs Free Documentation" and
"GNU Lesser General Public License", the Front-Cover texts being (a)
(see below), and with the Back-Cover Texts being (b) (see below).  A
copy of the license is included in the section entitled "GNU Free
Documentation License".

   (a) The FSF's Front-Cover Text is:

   A GNU Manual

   (b) The FSF's Back-Cover Text is:

   You have freedom to copy and modify this GNU Manual, like GNU
software.  Copies published by the Free Software Foundation raise
funds for GNU development.


File: libc.info,  Node: Synchronizing AIO Operations,  Next: Cancel AIO Operations,  Prev: Status of AIO Operations,  Up: Asynchronous I/O

Getting into a Consistent State
-------------------------------

   When dealing with asynchronous operations it is sometimes necessary
to get into a consistent state.  This would mean for AIO that one wants
to know whether a certain request or a group of request were processed.
This could be done by waiting for the notification sent by the system
after the operation terminated, but this sometimes would mean wasting
resources (mainly computation time).  Instead POSIX.1b defines two
functions which will help with most kinds of consistency.

   The `aio_fsync' and `aio_fsync64' functions are only available if
the symbol `_POSIX_SYNCHRONIZED_IO' is defined in `unistd.h'.

 - Function: int aio_fsync (int OP, struct aiocb *AIOCBP)
     Calling this function forces all I/O operations operating queued
     at the time of the function call operating on the file descriptor
     `aiocbp->aio_fildes' into the synchronized I/O completion state
     (*note Synchronizing I/O::).  The `aio_fsync' function returns
     immediately but the notification through the method described in
     `aiocbp->aio_sigevent' will happen only after all requests for this
     file descriptor have terminated and the file is synchronized.
     This also means that requests for this very same file descriptor
     which are queued after the synchronization request are not
     affected.

     If OP is `O_DSYNC' the synchronization happens as with a call to
     `fdatasync'.  Otherwise OP should be `O_SYNC' and the
     synchronization happens as with `fsync'.

     As long as the synchronization has not happened, a call to
     `aio_error' with the reference to the object pointed to by AIOCBP
     returns `EINPROGRESS'.  Once the synchronization is done
     `aio_error' return 0 if the synchronization was not successful.
     Otherwise the value returned is the value to which the `fsync' or
     `fdatasync' function would have set the `errno' variable.  In this
     case nothing can be assumed about the consistency for the data
     written to this file descriptor.

     The return value of this function is 0 if the request was
     successfully enqueued.  Otherwise the return value is -1 and
     `errno' is set to one of the following values:

    `EAGAIN'
          The request could not be enqueued due to temporary lack of
          resources.

    `EBADF'
          The file descriptor `aiocbp->aio_fildes' is not valid or not
          open for writing.

    `EINVAL'
          The implementation does not support I/O synchronization or
          the OP parameter is other than `O_DSYNC' and `O_SYNC'.

    `ENOSYS'
          This function is not implemented.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' this
     function is in fact `aio_return64' since the LFS interface
     transparently replaces the normal implementation.

 - Function: int aio_fsync64 (int OP, struct aiocb64 *AIOCBP)
     This function is similar to `aio_fsync' with the only difference
     that the argument is a reference to a variable of type `struct
     aiocb64'.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' this
     function is available under the name `aio_fsync' and so
     transparently replaces the interface for small files on 32 bit
     machines.

   Another method of synchronization is to wait until one or more
requests of a specific set terminated.  This could be achieved by the
`aio_*' functions to notify the initiating process about the
termination but in some situations this is not the ideal solution.  In
a program which constantly updates clients somehow connected to the
server it is not always the best solution to go round robin since some
connections might be slow.  On the other hand letting the `aio_*'
function notify the caller might also be not the best solution since
whenever the process works on preparing data for on client it makes no
sense to be interrupted by a notification since the new client will not
be handled before the current client is served.  For situations like
this `aio_suspend' should be used.

 - Function: int aio_suspend (const struct aiocb *const LIST[], int
          NENT, const struct timespec *TIMEOUT)
     When calling this function, the calling thread is suspended until
     at least one of the requests pointed to by the NENT elements of the
     array LIST has completed.  If any of the requests has already
     completed at the time `aio_suspend' is called, the function returns
     immediately.  Whether a request has terminated or not is
     determined by comparing the error status of the request with
     `EINPROGRESS'.  If an element of LIST is `NULL', the entry is
     simply ignored.

     If no request has finished, the calling process is suspended.  If
     TIMEOUT is `NULL', the process is not woken until a request has
     finished.  If TIMEOUT is not `NULL', the process remains suspended
     at least as long as specified in TIMEOUT.  In this case,
     `aio_suspend' returns with an error.

     The return value of the function is 0 if one or more requests from
     the LIST have terminated.  Otherwise the function returns -1 and
     `errno' is set to one of the following values:

    `EAGAIN'
          None of the requests from the LIST completed in the time
          specified by TIMEOUT.

    `EINTR'
          A signal interrupted the `aio_suspend' function.  This signal
          might also be sent by the AIO implementation while signalling
          the termination of one of the requests.

    `ENOSYS'
          The `aio_suspend' function is not implemented.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' this
     function is in fact `aio_suspend64' since the LFS interface
     transparently replaces the normal implementation.

 - Function: int aio_suspend64 (const struct aiocb64 *const LIST[], int
          NENT, const struct timespec *TIMEOUT)
     This function is similar to `aio_suspend' with the only difference
     that the argument is a reference to a variable of type `struct
     aiocb64'.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' this
     function is available under the name `aio_suspend' and so
     transparently replaces the interface for small files on 32 bit
     machines.


File: libc.info,  Node: Cancel AIO Operations,  Next: Configuration of AIO,  Prev: Synchronizing AIO Operations,  Up: Asynchronous I/O

Cancellation of AIO Operations
------------------------------

   When one or more requests are asynchronously processed, it might be
useful in some situations to cancel a selected operation, e.g., if it
becomes obvious that the written data is no longer accurate and would
have to be overwritten soon.  As an example, assume an application,
which writes data in files in a situation where new incoming data would
have to be written in a file which will be updated by an enqueued
request.  The POSIX AIO implementation provides such a function, but
this function is not capable of forcing the cancellation of the
request.  It is up to the implementation to decide whether it is
possible to cancel the operation or not.  Therefore using this function
is merely a hint.

 - Function: int aio_cancel (int FILDES, struct aiocb *AIOCBP)
     The `aio_cancel' function can be used to cancel one or more
     outstanding requests.  If the AIOCBP parameter is `NULL', the
     function tries to cancel all of the outstanding requests which
     would process the file descriptor FILDES (i.e., whose `aio_fildes'
     member is FILDES).  If AIOCBP is not `NULL', `aio_cancel' attempts
     to cancel the specific request pointed to by AIOCBP.

     For requests which were successfully canceled, the normal
     notification about the termination of the request should take
     place.  I.e., depending on the `struct sigevent' object which
     controls this, nothing happens, a signal is sent or a thread is
     started.  If the request cannot be canceled, it terminates the
     usual way after performing the operation.

     After a request is successfully canceled, a call to `aio_error'
     with a reference to this request as the parameter will return
     `ECANCELED' and a call to `aio_return' will return -1.  If the
     request wasn't canceled and is still running the error status is
     still `EINPROGRESS'.

     The return value of the function is `AIO_CANCELED' if there were
     requests which haven't terminated and which were successfully
     canceled.  If there is one or more requests left which couldn't be
     canceled, the return value is `AIO_NOTCANCELED'.  In this case
     `aio_error' must be used to find out which of the, perhaps
     multiple, requests (in AIOCBP is `NULL') weren't successfully
     canceled.  If all requests already terminated at the time
     `aio_cancel' is called the return value is `AIO_ALLDONE'.

     If an error occurred during the execution of `aio_cancel' the
     function returns -1 and sets `errno' to one of the following
     values.

    `EBADF'
          The file descriptor FILDES is not valid.

    `ENOSYS'
          `aio_cancel' is not implemented.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64', this
     function is in fact `aio_cancel64' since the LFS interface
     transparently replaces the normal implementation.

 - Function: int aio_cancel64 (int FILDES, struct aiocb64 *AIOCBP)
     This function is similar to `aio_cancel' with the only difference
     that the argument is a reference to a variable of type `struct
     aiocb64'.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64', this
     function is available under the name `aio_cancel' and so
     transparently replaces the interface for small files on 32 bit
     machines.


File: libc.info,  Node: Configuration of AIO,  Prev: Cancel AIO Operations,  Up: Asynchronous I/O

How to optimize the AIO implementation
--------------------------------------

   The POSIX standard does not specify how the AIO functions are
implemented.  They could be system calls, but it is also possible to
emulate them at userlevel.

   At the point of this writing, the available implementation is a
userlevel implementation which uses threads for handling the enqueued
requests.  While this implementation requires making some decisions
about limitations, hard limitations are something which is best avoided
in the GNU C library.  Therefore, the GNU C library provides a means
for tuning the AIO implementation according to the individual use.

 - Data Type: struct aioinit
     This data type is used to pass the configuration or tunable
     parameters to the implementation.  The program has to initialize
     the members of this struct and pass it to the implementation using
     the `aio_init' function.

    `int aio_threads'
          This member specifies the maximal number of threads which may
          be used at any one time.

    `int aio_num'
          This number provides an estimate on the maximal number of
          simultaneously enqueued requests.

    `int aio_locks'
          Unused.

    `int aio_usedba'
          Unused.

    `int aio_debug'
          Unused.

    `int aio_numusers'
          Unused.

    `int aio_reserved[2]'
          Unused.

 - Function: void aio_init (const struct aioinit *INIT)
     This function must be called before any other AIO function.
     Calling it is completely voluntary, as it is only meant to help
     the AIO implementation perform better.

     Before calling the `aio_init', function the members of a variable
     of type `struct aioinit' must be initialized.  Then a reference to
     this variable is passed as the parameter to `aio_init' which itself
     may or may not pay attention to the hints.

     The function has no return value and no error cases are defined.
     It is a extension which follows a proposal from the SGI
     implementation in Irix 6.  It is not covered by POSIX.1b or Unix98.


File: libc.info,  Node: Control Operations,  Next: Duplicating Descriptors,  Prev: Asynchronous I/O,  Up: Low-Level I/O

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 *Note 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).  *Note Duplicating
          Descriptors::.

    `F_GETFD'
          Get flags associated with the file descriptor.  *Note
          Descriptor Flags::.

    `F_SETFD'
          Set flags associated with the file descriptor.  *Note
          Descriptor Flags::.

    `F_GETFL'
          Get flags associated with the open file.  *Note File Status
          Flags::.

    `F_SETFL'
          Set flags associated with the open file.  *Note File Status
          Flags::.

    `F_GETLK'
          Get a file lock.  *Note File Locks::.

    `F_SETLK'
          Set or clear a file lock.  *Note File Locks::.

    `F_SETLKW'
          Like `F_SETLK', but wait for completion.  *Note File Locks::.

    `F_GETOWN'
          Get process or process group ID to receive `SIGIO' signals.
          *Note Interrupt Input::.

    `F_SETOWN'
          Set process or process group ID to receive `SIGIO' signals.
          *Note Interrupt Input::.

     This function is a cancellation point in multi-threaded programs.
     This is a problem if the thread allocates some resources (like
     memory, file descriptors, semaphores or whatever) at the time
     `fcntl' is called.  If the thread gets canceled these resources
     stay allocated until the program ends.  To avoid this calls to
     `fcntl' should be protected using cancellation handlers.


File: libc.info,  Node: Duplicating Descriptors,  Next: Descriptor Flags,  Prev: Control Operations,  Up: Low-Level I/O

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
(*note File Status Flags::), but each has its own set of file descriptor
flags (*note 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; *note
          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 (*note 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 *Note
Launching Jobs::.


File: libc.info,  Node: Descriptor Flags,  Next: File Status Flags,  Prev: Duplicating Descriptors,  Up: Low-Level I/O

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 (*note 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 *Note 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: libc.info,  Node: File Status Flags,  Next: File Locks,  Prev: Descriptor Flags,  Up: Low-Level I/O

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

   "File status flags" are used to specify attributes of the opening of
a file.  Unlike the file descriptor flags discussed in *Note 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'; *note Opening and Closing
Files::.

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

   * *Note 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.

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

   * *Note 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'.

* Menu:

* Access Modes::                Whether the descriptor can read or write.
* Open-time Flags::             Details of `open'.
* Operating Modes::             Special modes to control I/O operations.
* Getting File Status Flags::   Fetching and changing these flags.


File: libc.info,  Node: Access Modes,  Next: Open-time Flags,  Up: File Status Flags

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, and it never includes the
     `O_EXEC' bit.)


File: libc.info,  Node: Open-time Flags,  Next: Operating Modes,  Prev: Access Modes,  Up: File Status Flags

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.  *Note 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; when it is not meaningful, it is
     harmless and ignored.  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;
     *note 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.  *Note 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.  However, other
     systems may use a nonzero value for `O_NOCTTY' and set the
     controlling terminal when you open a file that is a terminal
     device; so to be portable, use `O_NOCTTY' when it is important to
     avoid this.

   The following 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.  *Note 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.

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

 - Macro: int O_SHLOCK
     Acquire a shared lock on the file, as with `flock'.  *Note 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'.  *Note
     File Locks::.  This is atomic like `O_SHLOCK'.


File: libc.info,  Node: Operating Modes,  Next: Getting File Status Flags,  Prev: Open-time Flags,  Up: File Status Flags

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.  This is the only
     reliable way to append to a file.  In append mode, you are
     guaranteed that the data you write will always go to the current
     end of the file, regardless of other processes writing to the
     file.  Conversely, if you simply set the file position to the end
     of file and write, then another process can extend the file after
     you set the file position but before you write, resulting in your
     data appearing someplace before the real end of file.

 - Macro: int 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; *note 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.  *Note
     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.  *Note File Times::.  This is used by programs that do
     backups, so that backing a file up does not count as reading it.
     Only the owner of the file or the superuser may use this bit.

     This is a GNU extension.


File: libc.info,  Node: Getting File Status Flags,  Prev: Operating Modes,  Up: File Status Flags

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: libc.info,  Node: File Locks,  Next: Interrupt Input,  Prev: File Status Flags,  Up: Low-Level I/O

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' (*note 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 (*note 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:

    `EAGAIN'
    `EACCES'
          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'.  (The GNU system always uses
          `EAGAIN'.)

    `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.

 - 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.
          *Note Interrupted Primitives::.

    `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.

   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.


File: libc.info,  Node: Interrupt Input,  Next: IOCTLs,  Prev: File Locks,  Up: Low-Level I/O

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

   If you set the `O_ASYNC' status flag on a file descriptor (*note
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 *Note Out-of-Band Data::.
(`SIGURG' is sent in any situation where `select' would report the
socket as having an "exceptional condition".  *Note 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.
*Note 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 *Note 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: libc.info,  Node: IOCTLs,  Prev: Interrupt Input,  Up: Low-Level I/O

Generic I/O Control operations
==============================

   The GNU system can handle most input/output operations on many
different devices and objects in terms of a few file primitives -
`read', `write' and `lseek'.  However, most devices also have a few
peculiar operations which do not fit into this model. Such as:

   * Changing the character font used on a terminal.

   * Telling a magnetic tape system to rewind or fast forward.  (Since
     they cannot move in byte increments, `lseek' is inapplicable).

   * Ejecting a disk from a drive.

   * Playing an audio track from a CD-ROM drive.

   * Maintaining routing tables for a network.


   Although some such objects such as sockets and terminals (1) have
special functions of their own, it would not be practical to create
functions for all these cases.

   Instead these minor operations, known as "IOCTL"s, are assigned code
numbers and multiplexed through the `ioctl' function, defined in
`sys/ioctl.h'.  The code numbers themselves are defined in many
different headers.

 - Function: int ioctl (int FILEDES, int COMMAND, ...)
     The `ioctl' function performs the generic I/O operation COMMAND on
     FILEDES.

     A third argument is usually present, either a single number or a
     pointer to a structure.  The meaning of this argument, the
     returned value, and any error codes depends upon the command used.
     Often -1 is returned for a failure.


   On some systems, IOCTLs used by different devices share the same
numbers.  Thus, although use of an inappropriate IOCTL _usually_ only
produces an error, you should not attempt to use device-specific IOCTLs
on an unknown device.

   Most IOCTLs are OS-specific and/or only used in special system
utilities, and are thus beyond the scope of this document.  For an
example of the use of an IOCTL, see *Note Out-of-Band Data::.

   ---------- Footnotes ----------

   (1) Actually, the terminal-specific functions are implemented with
IOCTLs on many platforms.

