This is Info file libc.info, produced by Makeinfo version 1.68 from the
input file 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.08 DRAFT, last updated 11 Jan 1999, of `The GNU C
Library Reference Manual', for Version 2.1 Beta.

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

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

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

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


File: libc.info,  Node: Permission Bits,  Next: Access Permission,  Prev: File Owner,  Up: File Attributes

The Mode Bits for Access Permission
-----------------------------------

   The "file mode", stored in the `st_mode' field of the file
attributes, contains two kinds of information: the file type code, and
the access permission bits.  This section discusses only the access
permission bits, which control who can read or write the file.  *Note
Testing File Type::, for information about the file type code.

   All of the symbols listed in this section are defined in the header
file `sys/stat.h'.

   These symbolic constants are defined for the file mode bits that
control access permission for the file:

`S_IRUSR'
`S_IREAD'
     Read permission bit for the owner of the file.  On many systems,
     this bit is 0400.  `S_IREAD' is an obsolete synonym provided for
     BSD compatibility.

`S_IWUSR'
`S_IWRITE'
     Write permission bit for the owner of the file.  Usually 0200.
     `S_IWRITE' is an obsolete synonym provided for BSD compatibility.

`S_IXUSR'
`S_IEXEC'
     Execute (for ordinary files) or search (for directories)
     permission bit for the owner of the file.  Usually 0100.
     `S_IEXEC' is an obsolete synonym provided for BSD compatibility.

`S_IRWXU'
     This is equivalent to `(S_IRUSR | S_IWUSR | S_IXUSR)'.

`S_IRGRP'
     Read permission bit for the group owner of the file.  Usually 040.

`S_IWGRP'
     Write permission bit for the group owner of the file.  Usually 020.

`S_IXGRP'
     Execute or search permission bit for the group owner of the file.
     Usually 010.

`S_IRWXG'
     This is equivalent to `(S_IRGRP | S_IWGRP | S_IXGRP)'.

`S_IROTH'
     Read permission bit for other users.  Usually 04.

`S_IWOTH'
     Write permission bit for other users.  Usually 02.

`S_IXOTH'
     Execute or search permission bit for other users.  Usually 01.

`S_IRWXO'
     This is equivalent to `(S_IROTH | S_IWOTH | S_IXOTH)'.

`S_ISUID'
     This is the set-user-ID on execute bit, usually 04000.  *Note How
     Change Persona::.

`S_ISGID'
     This is the set-group-ID on execute bit, usually 02000.  *Note How
     Change Persona::.

`S_ISVTX'
     This is the "sticky" bit, usually 01000.

     On a directory, it gives permission to delete a file in the
     directory only if you own that file.  Ordinarily, a user either
     can delete all the files in the directory or cannot delete any of
     them (based on whether the user has write permission for the
     directory).  The same restriction applies--you must both have
     write permission for the directory and own the file you want to
     delete.  The one exception is that the owner of the directory can
     delete any file in the directory, no matter who owns it (provided
     the owner has given himself write permission for the directory).
     This is commonly used for the `/tmp' directory, where anyone may
     create files, but not delete files created by other users.

     Originally the sticky bit on an executable file modified the
     swapping policies of the system.  Normally, when a program
     terminated, its pages in core were immediately freed and reused.
     If the sticky bit was set on the executable file, the system kept
     the pages in core for a while as if the program were still
     running.  This was advantageous for a program likely to be run
     many times in succession.  This usage is obsolete in modern
     systems.  When a program terminates, its pages always remain in
     core as long as there is no shortage of memory in the system.
     When the program is next run, its pages will still be in core if
     no shortage arose since the last run.

     On some modern systems where the sticky bit has no useful meaning
     for an executable file, you cannot set the bit at all for a
     non-directory.  If you try, `chmod' fails with `EFTYPE'; *note
     Setting Permissions::..

     Some systems (particularly SunOS) have yet another use for the
     sticky bit.  If the sticky bit is set on a file that is *not*
     executable, it means the opposite: never cache the pages of this
     file at all.  The main use of this is for the files on an NFS
     server machine which are used as the swap area of diskless client
     machines.  The idea is that the pages of the file will be cached
     in the client's memory, so it is a waste of the server's memory to
     cache them a second time.  In this use the sticky bit also says
     that the filesystem may fail to record the file's modification
     time onto disk reliably (the idea being that no-one cares for a
     swap file).

     This bit is only available on BSD systems (and those derived from
     them).  Therefore one has to use the `_BSD_SOURCE' feature select
     macro to get the definition (*note Feature Test Macros::.).

   The actual bit values of the symbols are listed in the table above
so you can decode file mode values when debugging your programs.  These
bit values are correct for most systems, but they are not guaranteed.

   *Warning:* Writing explicit numbers for file permissions is bad
practice.  It is not only non-portable, it also requires everyone who
reads your program to remember what the bits mean.  To make your
program clean, use the symbolic names.


File: libc.info,  Node: Access Permission,  Next: Setting Permissions,  Prev: Permission Bits,  Up: File Attributes

How Your Access to a File is Decided
------------------------------------

   Recall that the operating system normally decides access permission
for a file based on the effective user and group IDs of the process,
and its supplementary group IDs, together with the file's owner, group
and permission bits.  These concepts are discussed in detail in *Note
Process Persona::.

   If the effective user ID of the process matches the owner user ID of
the file, then permissions for read, write, and execute/search are
controlled by the corresponding "user" (or "owner") bits.  Likewise, if
any of the effective group ID or supplementary group IDs of the process
matches the group owner ID of the file, then permissions are controlled
by the "group" bits.  Otherwise, permissions are controlled by the
"other" bits.

   Privileged users, like `root', can access any file, regardless of
its file permission bits.  As a special case, for a file to be
executable even for a privileged user, at least one of its execute bits
must be set.


File: libc.info,  Node: Setting Permissions,  Next: Testing File Access,  Prev: Access Permission,  Up: File Attributes

Assigning File Permissions
--------------------------

   The primitive functions for creating files (for example, `open' or
`mkdir') take a MODE argument, which specifies the file permissions for
the newly created file.  But the specified mode is modified by the
process's "file creation mask", or "umask", before it is used.

   The bits that are set in the file creation mask identify permissions
that are always to be disabled for newly created files.  For example, if
you set all the "other" access bits in the mask, then newly created
files are not accessible at all to processes in the "other" category,
even if the MODE argument specified to the creation function would
permit such access.  In other words, the file creation mask is the
complement of the ordinary access permissions you want to grant.

   Programs that create files typically specify a MODE argument that
includes all the permissions that make sense for the particular file.
For an ordinary file, this is typically read and write permission for
all classes of users.  These permissions are then restricted as
specified by the individual user's own file creation mask.

   To change the permission of an existing file given its name, call
`chmod'.  This function ignores the file creation mask; it uses exactly
the specified permission bits.

   In normal use, the file creation mask is initialized in the user's
login shell (using the `umask' shell command), and inherited by all
subprocesses.  Application programs normally don't need to worry about
the file creation mask.  It will do automatically what it is supposed to
do.

   When your program should create a file and bypass the umask for its
access permissions, the easiest way to do this is to use `fchmod' after
opening the file, rather than changing the umask.

   In fact, changing the umask is usually done only by shells.  They use
the `umask' function.

   The functions in this section are declared in `sys/stat.h'.

 - Function: mode_t umask (mode_t MASK)
     The `umask' function sets the file creation mask of the current
     process to MASK, and returns the previous value of the file
     creation mask.

     Here is an example showing how to read the mask with `umask'
     without changing it permanently:

          mode_t
          read_umask (void)
          {
            mode_t mask = umask (0);
            umask (mask);
            return mask;
          }

     However, it is better to use `getumask' if you just want to read
     the mask value, because that is reentrant (at least if you use the
     GNU operating system).

 - Function: mode_t getumask (void)
     Return the current value of the file creation mask for the current
     process.  This function is a GNU extension.

 - Function: int chmod (const char *FILENAME, mode_t MODE)
     The `chmod' function sets the access permission bits for the file
     named by FILENAME to MODE.

     If the FILENAME names a symbolic link, `chmod' changes the
     permission of the file pointed to by the link, not those of the
     link itself.

     This function returns `0' if successful and `-1' if not.  In
     addition to the usual file name errors (*note File Name
     Errors::.), the following `errno' error conditions are defined for
     this function:

    `ENOENT'
          The named file doesn't exist.

    `EPERM'
          This process does not have permission to change the access
          permission of this file.  Only the file's owner (as judged by
          the effective user ID of the process) or a privileged user
          can change them.

    `EROFS'
          The file resides on a read-only file system.

    `EFTYPE'
          MODE has the `S_ISVTX' bit (the "sticky bit") set, and the
          named file is not a directory.  Some systems do not allow
          setting the sticky bit on non-directory files, and some do
          (and only some of those assign a useful meaning to the bit
          for non-directory files).

          You only get `EFTYPE' on systems where the sticky bit has no
          useful meaning for non-directory files, so it is always safe
          to just clear the bit in MODE and call `chmod' again.  *Note
          Permission Bits::, for full details on the sticky bit.

 - Function: int fchmod (int FILEDES, int MODE)
     This is like `chmod', except that it changes the permissions of
     the file currently open via descriptor FILEDES.

     The return value from `fchmod' is `0' on success and `-1' on
     failure.  The following `errno' error codes are defined for this
     function:

    `EBADF'
          The FILEDES argument is not a valid file descriptor.

    `EINVAL'
          The FILEDES argument corresponds to a pipe or socket, or
          something else that doesn't really have access permissions.

    `EPERM'
          This process does not have permission to change the access
          permission of this file.  Only the file's owner (as judged by
          the effective user ID of the process) or a privileged user
          can change them.

    `EROFS'
          The file resides on a read-only file system.


File: libc.info,  Node: Testing File Access,  Next: File Times,  Prev: Setting Permissions,  Up: File Attributes

Testing Permission to Access a File
-----------------------------------

   When a program runs as a privileged user, this permits it to access
files off-limits to ordinary users--for example, to modify
`/etc/passwd'.  Programs designed to be run by ordinary users but
access such files use the setuid bit feature so that they always run
with `root' as the effective user ID.

   Such a program may also access files specified by the user, files
which conceptually are being accessed explicitly by the user.  Since the
program runs as `root', it has permission to access whatever file the
user specifies--but usually the desired behavior is to permit only
those files which the user could ordinarily access.

   The program therefore must explicitly check whether *the user* would
have the necessary access to a file, before it reads or writes the file.

   To do this, use the function `access', which checks for access
permission based on the process's *real* user ID rather than the
effective user ID.  (The setuid feature does not alter the real user ID,
so it reflects the user who actually ran the program.)

   There is another way you could check this access, which is easy to
describe, but very hard to use.  This is to examine the file mode bits
and mimic the system's own access computation.  This method is
undesirable because many systems have additional access control
features; your program cannot portably mimic them, and you would not
want to try to keep track of the diverse features that different systems
have.  Using `access' is simple and automatically does whatever is
appropriate for the system you are using.

   `access' is *only* only appropriate to use in setuid programs.  A
non-setuid program will always use the effective ID rather than the
real ID.

   The symbols in this section are declared in `unistd.h'.

 - Function: int access (const char *FILENAME, int HOW)
     The `access' function checks to see whether the file named by
     FILENAME can be accessed in the way specified by the HOW argument.
     The HOW argument either can be the bitwise OR of the flags
     `R_OK', `W_OK', `X_OK', or the existence test `F_OK'.

     This function uses the *real* user and group ID's of the calling
     process, rather than the *effective* ID's, to check for access
     permission.  As a result, if you use the function from a `setuid'
     or `setgid' program (*note How Change Persona::.), it gives
     information relative to the user who actually ran the program.

     The return value is `0' if the access is permitted, and `-1'
     otherwise.  (In other words, treated as a predicate function,
     `access' returns true if the requested access is *denied*.)

     In addition to the usual file name errors (*note File Name
     Errors::.), the following `errno' error conditions are defined for
     this function:

    `EACCES'
          The access specified by HOW is denied.

    `ENOENT'
          The file doesn't exist.

    `EROFS'
          Write permission was requested for a file on a read-only file
          system.

   These macros are defined in the header file `unistd.h' for use as
the HOW argument to the `access' function.  The values are integer
constants.

 - Macro: int R_OK
     Argument that means, test for read permission.

 - Macro: int W_OK
     Argument that means, test for write permission.

 - Macro: int X_OK
     Argument that means, test for execute/search permission.

 - Macro: int F_OK
     Argument that means, test for existence of the file.


File: libc.info,  Node: File Times,  Next: File Size,  Prev: Testing File Access,  Up: File Attributes

File Times
----------

   Each file has three time stamps associated with it:  its access time,
its modification time, and its attribute modification time.  These
correspond to the `st_atime', `st_mtime', and `st_ctime' members of the
`stat' structure; see *Note File Attributes::.

   All of these times are represented in calendar time format, as
`time_t' objects.  This data type is defined in `time.h'.  For more
information about representation and manipulation of time values, see
*Note Calendar Time::.

   Reading from a file updates its access time attribute, and writing
updates its modification time.  When a file is created, all three time
stamps for that file are set to the current time.  In addition, the
attribute change time and modification time fields of the directory that
contains the new entry are updated.

   Adding a new name for a file with the `link' function updates the
attribute change time field of the file being linked, and both the
attribute change time and modification time fields of the directory
containing the new name.  These same fields are affected if a file name
is deleted with `unlink', `remove', or `rmdir'.  Renaming a file with
`rename' affects only the attribute change time and modification time
fields of the two parent directories involved, and not the times for
the file being renamed.

   Changing attributes of a file (for example, with `chmod') updates
its attribute change time field.

   You can also change some of the time stamps of a file explicitly
using the `utime' function--all except the attribute change time.  You
need to include the header file `utime.h' to use this facility.

 - Data Type: struct utimbuf
     The `utimbuf' structure is used with the `utime' function to
     specify new access and modification times for a file.  It contains
     the following members:

    `time_t actime'
          This is the access time for the file.

    `time_t modtime'
          This is the modification time for the file.

 - Function: int utime (const char *FILENAME, const struct utimbuf
          *TIMES)
     This function is used to modify the file times associated with the
     file named FILENAME.

     If TIMES is a null pointer, then the access and modification times
     of the file are set to the current time.  Otherwise, they are set
     to the values from the `actime' and `modtime' members
     (respectively) of the `utimbuf' structure pointed at by TIMES.

     The attribute modification time for the file is set to the current
     time in either case (since changing the time stamps is itself a
     modification of the file attributes).

     The `utime' function returns `0' if successful and `-1' on
     failure.  In addition to the usual file name errors (*note File
     Name Errors::.), the following `errno' error conditions are
     defined for this function:

    `EACCES'
          There is a permission problem in the case where a null
          pointer was passed as the TIMES argument.  In order to update
          the time stamp on the file, you must either be the owner of
          the file, have write permission on the file, or be a
          privileged user.

    `ENOENT'
          The file doesn't exist.

    `EPERM'
          If the TIMES argument is not a null pointer, you must either
          be the owner of the file or be a privileged user.  This error
          is used to report the problem.

    `EROFS'
          The file lives on a read-only file system.

   Each of the three time stamps has a corresponding microsecond part,
which extends its resolution.  These fields are called `st_atime_usec',
`st_mtime_usec', and `st_ctime_usec'; each has a value between 0 and
999,999, which indicates the time in microseconds.  They correspond to
the `tv_usec' field of a `timeval' structure; see *Note High-Resolution
Calendar::.

   The `utimes' function is like `utime', but also lets you specify the
fractional part of the file times.  The prototype for this function is
in the header file `sys/time.h'.

 - Function: int utimes (const char *FILENAME, struct timeval TVP[2])
     This function sets the file access and modification times for the
     file named by FILENAME.  The new file access time is specified by
     `TVP[0]', and the new modification time by `TVP[1]'.  This
     function comes from BSD.

     The return values and error conditions are the same as for the
     `utime' function.


File: libc.info,  Node: File Size,  Prev: File Times,  Up: File Attributes

File Size
---------

   Normally file sizes are maintained automatically.  A file begins
with a size of 0 and is automatically extended when data is written
past its end.  It is also possible to empty a file completely in an
`open' or `fopen' call.

   However, sometimes it is neccessary to *reduce* the size of a file.
This can be done with the `truncate' and `ftruncate' functions.  They
were introduced in BSD Unix.  `ftruncate' was later added to POSIX.1.

   Some systems allow you to extend a file (creating holes) with these
functions.  This is useful when using memory-mapped I/O (*note
Memory-mapped I/O::.), where files are not automatically extended.
However it is not portable but must be implemented if `mmap' allows
mapping of files (i.e., `_POSIX_MAPPED_FILES' is defined).

   Using these functions on anything other than a regular file gives
*undefined* results.  On many systems, such a call will appear to
succeed, without actually accomplishing anything.

 - Function: int truncate (const char *FILENAME, off_t LENGTH)
     The `truncate' function changes the size of FILENAME to LENGTH.
     If LENGTH is shorter than the previous length, data at the end
     will be lost.

     If LENGTH is longer, holes will be added to the end.  However, some
     systems do not support this feature and will leave the file
     unchanged.

     The return value is 0 for success, or -1 for an error.  In
     addition to the usual file name errors, the following errors may
     occur:

    `EACCES'
          The file is a directory or not writable.

    `EINVAL'
          LENGTH is negative.

    `EFBIG'
          The operation would extend the file beyond the limits of the
          operating system.

    `EIO'
          A hardware I/O error occured.

    `EPERM'
          The file is "append-only" or "immutable".

    `EINTR'
          The operation was interrupted by a signal.


 - Function: int ftruncate (int FD, off_t LENGTH)
     This is like `truncate', but it works on a file descriptor FD.

     `ftruncate' is especially useful in combination with `mmap'.
     Since the mapped region must have a fixed size one cannot enlarge
     the file by writing something beyond the last mapped page.
     Instead one has to enlarge the file itself and then remap the file
     with the new size.  The example below shows how this works.

     The return value is 0 for success, or -1 for an error.  The
     following errors may occur:

    `EBADF'
          FD does not correspond to an open file.

    `EACCES'
          FD is a directory or not open for write.

    `EINVAL'
          LENGTH is negative.

    `EFBIG'
          The operation would extend the file beyond the limits of the
          operating system.

    `EIO'
          A hardware I/O error occured.

    `EPERM'
          The file is "append-only" or "immutable".

    `EINTR'
          The operation was interrupted by a signal.


   As announced here is a little example how to use `ftruncate' in
combination with `mmap':

     int fd;
     void *start;
     size_t len;
     
     int
     add (off_t at, void *block, size_t size)
     {
       if (at + size > len)
         {
           /* Resize the file and remap.  */
           size_t ps = sysconf (_SC_PAGESIZE);
           size_t ns = (at + size + ps - 1) & ~(ps - 1);
           void *np;
           if (ftruncate (fd, ns) < 0)
             return -1;
           np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
           if (np == MAP_FAILED)
             return -1;
           start = np;
           len = ns;
         }
       memcpy ((char *) start + at, block, size);
       return 0;
     }

   The function `add' allows to add at arbitrary positions in the file
given blocks of memory.  If the current size of the file is too small it
is extended.  Please note the it is extended in multiples of a pagesize.
This is a requirement of `mmap'.  The program has to track the real
size and once the program finished to work a final `ftruncate' call
should set the real size of the file.


File: libc.info,  Node: Making Special Files,  Next: Temporary Files,  Prev: File Attributes,  Up: File System Interface

Making Special Files
====================

   The `mknod' function is the primitive for making special files, such
as files that correspond to devices.  The GNU library includes this
function for compatibility with BSD.

   The prototype for `mknod' is declared in `sys/stat.h'.

 - Function: int mknod (const char *FILENAME, int MODE, int DEV)
     The `mknod' function makes a special file with name FILENAME.  The
     MODE specifies the mode of the file, and may include the various
     special file bits, such as `S_IFCHR' (for a character special file)
     or `S_IFBLK' (for a block special file).  *Note Testing File
     Type::.

     The DEV argument specifies which device the special file refers to.
     Its exact interpretation depends on the kind of special file being
     created.

     The return value is `0' on success and `-1' on error.  In addition
     to the usual file name errors (*note File Name Errors::.), the
     following `errno' error conditions are defined for this function:

    `EPERM'
          The calling process is not privileged.  Only the superuser
          can create special files.

    `ENOSPC'
          The directory or file system that would contain the new file
          is full and cannot be extended.

    `EROFS'
          The directory containing the new file can't be modified
          because it's on a read-only file system.

    `EEXIST'
          There is already a file named FILENAME.  If you want to
          replace this file, you must remove the old file explicitly
          first.


File: libc.info,  Node: Temporary Files,  Prev: Making Special Files,  Up: File System Interface

Temporary Files
===============

   If you need to use a temporary file in your program, you can use the
`tmpfile' function to open it.  Or you can use the `tmpnam' (better:
`tmpnam_r') function to make a name for a temporary file and then you
can open it in the usual way with `fopen'.

   The `tempnam' function is like `tmpnam' but lets you choose what
directory temporary files will go in, and something about what their
file names will look like.  Important for multi threaded programs is
that `tempnam' is reentrant while `tmpnam' is not since it returns a
pointer to a static buffer.

   These facilities are declared in the header file `stdio.h'.

 - Function: FILE * tmpfile (void)
     This function creates a temporary binary file for update mode, as
     if by calling `fopen' with mode `"wb+"'.  The file is deleted
     automatically when it is closed or when the program terminates.
     (On some other ISO C systems the file may fail to be deleted if
     the program terminates abnormally).

     This function is reentrant.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' on a
     32 bits system this function is in fact `tmpfile64'.  I.e., the
     LFS interface transparently replaces the old interface.

 - Function: FILE * tmpfile64 (void)
     This function is similar to `tmpfile' but the stream it returns a
     pointer for is opened using `tmpfile64'.  Therefore this stream
     can be used even on files larger then 2^31 bytes on 32 bits
     machines.

     Please note that the return type is still `FILE *'.  There is no
     special `FILE' type for the LFS interface.

     If the sources are compiled with `_FILE_OFFSET_BITS == 64' on a 32
     bits machine this function is available under the name `tmpfile'
     and so transparently replaces the old interface.

 - Function: char * tmpnam (char *RESULT)
     This function constructs and returns a file name that is a valid
     file name and that does not name any existing file.  If the RESULT
     argument is a null pointer, the return value is a pointer to an
     internal static string, which might be modified by subsequent
     calls and therefore makes this function non-reentrant.  Otherwise,
     the RESULT argument should be a pointer to an array of at least
     `L_tmpnam' characters, and the result is written into that array.

     It is possible for `tmpnam' to fail if you call it too many times
     without removing previously created files.  This is because the
     fixed length of a temporary file name gives room for only a finite
     number of different names.  If `tmpnam' fails, it returns a null
     pointer.

     *Warning:* Since between the time the pathname is constructed and
     the file is created another process might have created a file with
     this name using `tmpnam' is a possible security hole.  The
     implementation generates names which hardly can be predicted but
     opening the file in any case should use the `O_EXCL' flag.  Using
     `tmpfile' is a safe way to avoid this problem.

 - Function: char * tmpnam_r (char *RESULT)
     This function is nearly identical to the `tmpnam' function.  But it
     does not allow RESULT to be a null pointer.  In the later case a
     null pointer is returned.

     This function is reentrant because the non-reentrant situation of
     `tmpnam' cannot happen here.

 - Macro: int L_tmpnam
     The value of this macro is an integer constant expression that
     represents the minimum allocation size of a string large enough to
     hold the file name generated by the `tmpnam' function.

 - Macro: int TMP_MAX
     The macro `TMP_MAX' is a lower bound for how many temporary names
     you can create with `tmpnam'.  You can rely on being able to call
     `tmpnam' at least this many times before it might fail saying you
     have made too many temporary file names.

     With the GNU library, you can create a very large number of
     temporary file names--if you actually create the files, you will
     probably run out of disk space before you run out of names.  Some
     other systems have a fixed, small limit on the number of temporary
     files.  The limit is never less than `25'.

 - Function: char * tempnam (const char *DIR, const char *PREFIX)
     This function generates a unique temporary filename.  If PREFIX is
     not a null pointer, up to five characters of this string are used
     as a prefix for the file name.  The return value is a string newly
     allocated with `malloc'; you should release its storage with
     `free' when it is no longer needed.

     Because the string is dynamically allocated this function is
     reentrant.

     The directory prefix for the temporary file name is determined by
     testing each of the following, in sequence.  The directory must
     exist and be writable.

        * The environment variable `TMPDIR', if it is defined.  For
          security reasons this only happens if the program is not SUID
          or SGID enabled.

        * The DIR argument, if it is not a null pointer.

        * The value of the `P_tmpdir' macro.

        * The directory `/tmp'.

     This function is defined for SVID compatibility.

 - SVID Macro: char * P_tmpdir
     This macro is the name of the default directory for temporary
     files.

   Older Unix systems did not have the functions just described.
Instead they used `mktemp' and `mkstemp'.  Both of these functions work
by modifying a file name template string you pass.  The last six
characters of this string must be `XXXXXX'.  These six `X's are
replaced with six characters which make the whole string a unique file
name.  Usually the template string is something like
`/tmp/PREFIXXXXXXX', and each program uses a unique PREFIX.

   *Note:* Because `mktemp' and `mkstemp' modify the template string,
you *must not* pass string constants to them.  String constants are
normally in read-only storage, so your program would crash when
`mktemp' or `mkstemp' tried to modify the string.

 - Function: char * mktemp (char *TEMPLATE)
     The `mktemp' function generates a unique file name by modifying
     TEMPLATE as described above.  If successful, it returns TEMPLATE
     as modified.  If `mktemp' cannot find a unique file name, it makes
     TEMPLATE an empty string and returns that.  If TEMPLATE does not
     end with `XXXXXX', `mktemp' returns a null pointer.

     *Warning:* Since between the time the pathname is constructed and
     the file is created another process might have created a file with
     this name using `mktemp' is a possible security hole.  The
     implementation generates names which hardly can be predicted but
     opening the file in any case should use the `O_EXCL' flag.  Using
     `mkstemp' is a safe way to avoid this problem.

 - Function: int mkstemp (char *TEMPLATE)
     The `mkstemp' function generates a unique file name just as
     `mktemp' does, but it also opens the file for you with `open'
     (*note Opening and Closing Files::.).  If successful, it modifies
     TEMPLATE in place and returns a file descriptor open on that file
     for reading and writing.  If `mkstemp' cannot create a
     uniquely-named file, it returns `-1'.  If TEMPLATE does not end
     with `XXXXXX', `mkstemp' returns `-1' and does not modify TEMPLATE.

     The file is opened using mode `0600'.  If the file is meant to be
     used by other users the mode must explicitly changed.

   Unlike `mktemp', `mkstemp' is actually guaranteed to create a unique
file that cannot possibly clash with any other program trying to create
a temporary file.  This is because it works by calling `open' with the
`O_EXCL' flag bit, which says you want to always create a new file, and
get an error if the file already exists.


File: libc.info,  Node: Pipes and FIFOs,  Next: Sockets,  Prev: File System Interface,  Up: Top

Pipes and FIFOs
***************

   A "pipe" is a mechanism for interprocess communication; data written
to the pipe by one process can be read by another process.  The data is
handled in a first-in, first-out (FIFO) order.  The pipe has no name; it
is created for one use and both ends must be inherited from the single
process which created the pipe.

   A "FIFO special file" is similar to a pipe, but instead of being an
anonymous, temporary connection, a FIFO has a name or names like any
other file.  Processes open the FIFO by name in order to communicate
through it.

   A pipe or FIFO has to be open at both ends simultaneously.  If you
read from a pipe or FIFO file that doesn't have any processes writing
to it (perhaps because they have all closed the file, or exited), the
read returns end-of-file.  Writing to a pipe or FIFO that doesn't have a
reading process is treated as an error condition; it generates a
`SIGPIPE' signal, and fails with error code `EPIPE' if the signal is
handled or blocked.

   Neither pipes nor FIFO special files allow file positioning.  Both
reading and writing operations happen sequentially; reading from the
beginning of the file and writing at the end.

* Menu:

* Creating a Pipe::             Making a pipe with the `pipe' function.
* Pipe to a Subprocess::        Using a pipe to communicate with a
				 child process.
* FIFO Special Files::          Making a FIFO special file.
* Pipe Atomicity::		When pipe (or FIFO) I/O is atomic.


File: libc.info,  Node: Creating a Pipe,  Next: Pipe to a Subprocess,  Up: Pipes and FIFOs

Creating a Pipe
===============

   The primitive for creating a pipe is the `pipe' function.  This
creates both the reading and writing ends of the pipe.  It is not very
useful for a single process to use a pipe to talk to itself.  In typical
use, a process creates a pipe just before it forks one or more child
processes (*note Creating a Process::.).  The pipe is then used for
communication either between the parent or child processes, or between
two sibling processes.

   The `pipe' function is declared in the header file `unistd.h'.

 - Function: int pipe (int FILEDES[2])
     The `pipe' function creates a pipe and puts the file descriptors
     for the reading and writing ends of the pipe (respectively) into
     `FILEDES[0]' and `FILEDES[1]'.

     An easy way to remember that the input end comes first is that file
     descriptor `0' is standard input, and file descriptor `1' is
     standard output.

     If successful, `pipe' returns a value of `0'.  On failure, `-1' is
     returned.  The following `errno' error conditions are defined for
     this function:

    `EMFILE'
          The process has too many files open.

    `ENFILE'
          There are too many open files in the entire system.  *Note
          Error Codes::, for more information about `ENFILE'.  This
          error never occurs in the GNU system.

   Here is an example of a simple program that creates a pipe.  This
program uses the `fork' function (*note Creating a Process::.) to create
a child process.  The parent process writes data to the pipe, which is
read by the child process.

     #include <sys/types.h>
     #include <unistd.h>
     #include <stdio.h>
     #include <stdlib.h>
     
     /* Read characters from the pipe and echo them to `stdout'. */
     
     void
     read_from_pipe (int file)
     {
       FILE *stream;
       int c;
       stream = fdopen (file, "r");
       while ((c = fgetc (stream)) != EOF)
         putchar (c);
       fclose (stream);
     }
     
     /* Write some random text to the pipe. */
     
     void
     write_to_pipe (int file)
     {
       FILE *stream;
       stream = fdopen (file, "w");
       fprintf (stream, "hello, world!\n");
       fprintf (stream, "goodbye, world!\n");
       fclose (stream);
     }
     
     int
     main (void)
     {
       pid_t pid;
       int mypipe[2];
     /* Create the pipe. */
       if (pipe (mypipe))
         {
           fprintf (stderr, "Pipe failed.\n");
           return EXIT_FAILURE;
         }
     
       /* Create the child process. */
       pid = fork ();
       if (pid == (pid_t) 0)
         {
           /* This is the child process. */
           read_from_pipe (mypipe[0]);
           return EXIT_SUCCESS;
         }
       else if (pid < (pid_t) 0)
         {
           /* The fork failed. */
           fprintf (stderr, "Fork failed.\n");
           return EXIT_FAILURE;
         }
       else
         {
           /* This is the parent process. */
           write_to_pipe (mypipe[1]);
           return EXIT_SUCCESS;
         }
     }


File: libc.info,  Node: Pipe to a Subprocess,  Next: FIFO Special Files,  Prev: Creating a Pipe,  Up: Pipes and FIFOs

Pipe to a Subprocess
====================

   A common use of pipes is to send data to or receive data from a
program being run as subprocess.  One way of doing this is by using a
combination of `pipe' (to create the pipe), `fork' (to create the
subprocess), `dup2' (to force the subprocess to use the pipe as its
standard input or output channel), and `exec' (to execute the new
program).  Or, you can use `popen' and `pclose'.

   The advantage of using `popen' and `pclose' is that the interface is
much simpler and easier to use.  But it doesn't offer as much
flexibility as using the low-level functions directly.

 - Function: FILE * popen (const char *COMMAND, const char *MODE)
     The `popen' function is closely related to the `system' function;
     see *Note Running a Command::.  It executes the shell command
     COMMAND as a subprocess.  However, instead of waiting for the
     command to complete, it creates a pipe to the subprocess and
     returns a stream that corresponds to that pipe.

     If you specify a MODE argument of `"r"', you can read from the
     stream to retrieve data from the standard output channel of the
     subprocess.  The subprocess inherits its standard input channel
     from the parent process.

     Similarly, if you specify a MODE argument of `"w"', you can write
     to the stream to send data to the standard input channel of the
     subprocess.  The subprocess inherits its standard output channel
     from the parent process.

     In the event of an error, `popen' returns a null pointer.  This
     might happen if the pipe or stream cannot be created, if the
     subprocess cannot be forked, or if the program cannot be executed.

 - Function: int pclose (FILE *STREAM)
     The `pclose' function is used to close a stream created by `popen'.
     It waits for the child process to terminate and returns its status
     value, as for the `system' function.

   Here is an example showing how to use `popen' and `pclose' to filter
output through another program, in this case the paging program `more'.

     #include <stdio.h>
     #include <stdlib.h>
     
     void
     write_data (FILE * stream)
     {
       int i;
       for (i = 0; i < 100; i++)
         fprintf (stream, "%d\n", i);
       if (ferror (stream))
         {
           fprintf (stderr, "Output to stream failed.\n");
           exit (EXIT_FAILURE);
         }
     }
     int
     main (void)
     {
       FILE *output;
     
       output = popen ("more", "w");
       if (!output)
         {
           fprintf (stderr, "Could not run more.\n");
           return EXIT_FAILURE;
         }
       write_data (output);
       pclose (output);
       return EXIT_SUCCESS;
     }


File: libc.info,  Node: FIFO Special Files,  Next: Pipe Atomicity,  Prev: Pipe to a Subprocess,  Up: Pipes and FIFOs

FIFO Special Files
==================

   A FIFO special file is similar to a pipe, except that it is created
in a different way.  Instead of being an anonymous communications
channel, a FIFO special file is entered into the file system by calling
`mkfifo'.

   Once you have created a FIFO special file in this way, any process
can open it for reading or writing, in the same way as an ordinary file.
However, it has to be open at both ends simultaneously before you can
proceed to do any input or output operations on it.  Opening a FIFO for
reading normally blocks until some other process opens the same FIFO for
writing, and vice versa.

   The `mkfifo' function is declared in the header file `sys/stat.h'.

 - Function: int mkfifo (const char *FILENAME, mode_t MODE)
     The `mkfifo' function makes a FIFO special file with name
     FILENAME.  The MODE argument is used to set the file's
     permissions; see *Note Setting Permissions::.

     The normal, successful return value from `mkfifo' is `0'.  In the
     case of an error, `-1' is returned.  In addition to the usual file
     name errors (*note File Name Errors::.), the following `errno'
     error conditions are defined for this function:

    `EEXIST'
          The named file already exists.

    `ENOSPC'
          The directory or file system cannot be extended.

    `EROFS'
          The directory that would contain the file resides on a
          read-only file system.


File: libc.info,  Node: Pipe Atomicity,  Prev: FIFO Special Files,  Up: Pipes and FIFOs

Atomicity of Pipe I/O
=====================

   Reading or writing pipe data is "atomic" if the size of data written
is not greater than `PIPE_BUF'.  This means that the data transfer
seems to be an instantaneous unit, in that nothing else in the system
can observe a state in which it is partially complete.  Atomic I/O may
not begin right away (it may need to wait for buffer space or for data),
but once it does begin, it finishes immediately.

   Reading or writing a larger amount of data may not be atomic; for
example, output data from other processes sharing the descriptor may be
interspersed.  Also, once `PIPE_BUF' characters have been written,
further writes will block until some characters are read.

   *Note Limits for Files::, for information about the `PIPE_BUF'
parameter.


File: libc.info,  Node: Sockets,  Next: Low-Level Terminal Interface,  Prev: Pipes and FIFOs,  Up: Top

Sockets
*******

   This chapter describes the GNU facilities for interprocess
communication using sockets.

   A "socket" is a generalized interprocess communication channel.
Like a pipe, a socket is represented as a file descriptor.  But, unlike
pipes, sockets support communication between unrelated processes, and
even between processes running on different machines that communicate
over a network.  Sockets are the primary means of communicating with
other machines; `telnet', `rlogin', `ftp', `talk', and the other
familiar network programs use sockets.

   Not all operating systems support sockets.  In the GNU library, the
header file `sys/socket.h' exists regardless of the operating system,
and the socket functions always exist, but if the system does not
really support sockets, these functions always fail.

   *Incomplete:* We do not currently document the facilities for
broadcast messages or for configuring Internet interfaces.  The
reentrant functions and some newer functions that are related to IPv6
aren't documented either so far.

* Menu:

* Socket Concepts::	Basic concepts you need to know about.
* Communication Styles::Stream communication, datagrams, and other styles.
* Socket Addresses::	How socket names ("addresses") work.
* Interface Naming::	Identifying specific network interfaces.
* Local Namespace::	Details about the local namespace.
* Internet Namespace::	Details about the Internet namespace.
* Misc Namespaces::	Other namespaces not documented fully here.
* Open/Close Sockets::  Creating sockets and destroying them.
* Connections::		Operations on sockets with connection state.
* Datagrams::		Operations on datagram sockets.
* Inetd::		Inetd is a daemon that starts servers on request.
			   The most convenient way to write a server
			   is to make it work with Inetd.
* Socket Options::	Miscellaneous low-level socket options.
* Networks Database::   Accessing the database of network names.


File: libc.info,  Node: Socket Concepts,  Next: Communication Styles,  Up: Sockets

Socket Concepts
===============

   When you create a socket, you must specify the style of communication
you want to use and the type of protocol that should implement it.  The
"communication style" of a socket defines the user-level semantics of
sending and receiving data on the socket.  Choosing a communication
style specifies the answers to questions such as these:

   * *What are the units of data transmission?*  Some communication
     styles regard the data as a sequence of bytes, with no larger
     structure; others group the bytes into records (which are known in
     this context as "packets").

   * *Can data be lost during normal operation?*  Some communication
     styles guarantee that all the data sent arrives in the order it was
     sent (barring system or network crashes); other styles occasionally
     lose data as a normal part of operation, and may sometimes deliver
     packets more than once or in the wrong order.

     Designing a program to use unreliable communication styles usually
     involves taking precautions to detect lost or misordered packets
     and to retransmit data as needed.

   * *Is communication entirely with one partner?*  Some communication
     styles are like a telephone call--you make a "connection" with one
     remote socket, and then exchange data freely.  Other styles are
     like mailing letters--you specify a destination address for each
     message you send.

   You must also choose a "namespace" for naming the socket.  A socket
name ("address") is meaningful only in the context of a particular
namespace.  In fact, even the data type to use for a socket name may
depend on the namespace.  Namespaces are also called "domains", but we
avoid that word as it can be confused with other usage of the same
term.  Each namespace has a symbolic name that starts with `PF_'.  A
corresponding symbolic name starting with `AF_' designates the address
format for that namespace.

   Finally you must choose the "protocol" to carry out the
communication.  The protocol determines what low-level mechanism is used
to transmit and receive data.  Each protocol is valid for a particular
namespace and communication style; a namespace is sometimes called a
"protocol family" because of this, which is why the namespace names
start with `PF_'.

   The rules of a protocol apply to the data passing between two
programs, perhaps on different computers; most of these rules are
handled by the operating system, and you need not know about them.
What you do need to know about protocols is this:

   * In order to have communication between two sockets, they must
     specify the *same* protocol.

   * Each protocol is meaningful with particular style/namespace
     combinations and cannot be used with inappropriate combinations.
     For example, the TCP protocol fits only the byte stream style of
     communication and the Internet namespace.

   * For each combination of style and namespace, there is a "default
     protocol" which you can request by specifying 0 as the protocol
     number.  And that's what you should normally do--use the default.

   Throughout the following description at various places
variables/parameters to denote sizes are required.  And here the trouble
starts.  In the first implementations the type of these variables was
simply `int'.  This type was on almost all machines of this time 32
bits wide and so a de-factor standard required 32 bit variables.  This
is important since references to variables of this type are passed to
the kernel.

   But then the POSIX people came and unified the interface with the
words "all size values are of type `size_t'".  But on 64 bit machines
`size_t' is 64 bits wide, and so variable references are not anymore
possible.

   The Unix98 specification provides a solution by introducing a type
`socklen_t'.  This type is used in all of the cases that POSIX changed
to use `size_t'.  The only requirement of this type is that it be an
unsigned type of at least 32 bits.  Therefore, implementations which
require that references to 32 bit variables be passed can be as happy
as implementations which use 64 bit values.

