   This file documents the GNU C library.

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

   Copyright (C) 1993, 1994 Free Software Foundation, Inc.

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

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

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

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)
          {
            mask = umask (0);
            umask (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 syntax errors (see 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.  See
          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.

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 (see 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 syntax errors (see 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 Times
----------

   Each file has three timestamps 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 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
Calendar Time.

   When an existing file is opened, its attribute change time and
modification time fields are updated.  Reading from a file updates its
access time attribute, and writing updates its modification time.

   When a file is created, all three timestamps 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 timestamps 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 timestamps 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 syntax errors (see
     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 timestamp 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 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.

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).  See 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 syntax errors (see 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.

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' function
make a name for a temporary file and then 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.

   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 ANSI C systems the file may fail to be deleted if
     the program terminates abnormally).

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

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

     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.

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

 - 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'
     (see 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 makes TEMPLATE an empty string and returns
     `-1'.  If TEMPLATE does not end with `XXXXXX', `mkstemp' returns
     `-1' and does not modify TEMPLATE.

   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.

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.

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 (see 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.  See
          Error Codes, for more information about `ENFILE'.

   Here is an example of a simple program that creates a pipe.  This
program uses the `fork' function (see 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;
         }
     }

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

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 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 syntax errors (see 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.

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

   Reading or writing pipe data is "atomic" if the size of data written
is less 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.

   See Limits for Files, for information about the `PIPE_BUF'
parameter.

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.

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.

Communication Styles
====================

   The GNU library includes support for several different kinds of
sockets, each with different characteristics.  This section describes
the supported socket types.  The symbolic constants listed here are
defined in `sys/socket.h'.

 - Macro: int SOCK_STREAM
     The `SOCK_STREAM' style is like a pipe (see Pipes and FIFOs.);
     it operates over a connection with a particular remote socket, and
     transmits data reliably as a stream of bytes.

     Use of this style is covered in detail in Connections.

 - Macro: int SOCK_DGRAM
     The `SOCK_DGRAM' style is used for sending individually-addressed
     packets, unreliably.  It is the diametrical opposite of
     `SOCK_STREAM'.

     Each time you write data to a socket of this kind, that data
     becomes one packet.  Since `SOCK_DGRAM' sockets do not have
     connections, you must specify the recipient address with each
     packet.

     The only guarantee that the system makes about your requests to
     transmit data is that it will try its best to deliver each packet
     you send.  It may succeed with the sixth packet after failing with
     the fourth and fifth packets; the seventh packet may arrive before
     the sixth, and may arrive a second time after the sixth.

     The typical use for `SOCK_DGRAM' is in situations where it is
     acceptable to simply resend a packet if no response is seen in a
     reasonable amount of time.

     See Datagrams, for detailed information about how to use
     datagram sockets.

 - Macro: int SOCK_RAW
     This style provides access to low-level network protocols and
     interfaces.  Ordinary user programs usually have no need to use
     this style.

Socket Addresses
================

   The name of a socket is normally called an "address".  The functions
and symbols for dealing with socket addresses were named
inconsistently, sometimes using the term "name" and sometimes using
"address".  You can regard these terms as synonymous where sockets are
concerned.

   A socket newly created with the `socket' function has no address.
Other processes can find it for communication only if you give it an
address.  We call this "binding" the address to the socket, and the way
to do it is with the `bind' function.

   You need be concerned with the address of a socket if other processes
are to find it and start communicating with it.  You can specify an
address for other sockets, but this is usually pointless; the first time
you send data from a socket, or use it to initiate a connection, the
system assigns an address automatically if you have not specified one.

   Occasionally a client needs to specify an address because the server
discriminates based on addresses; for example, the rsh and rlogin
protocols look at the client's socket address and don't bypass password
checking unless it is less than `IPPORT_RESERVED' (see Ports.).

   The details of socket addresses vary depending on what namespace you
are using.  See File Namespace, or Internet Namespace, for
specific information.

   Regardless of the namespace, you use the same functions `bind' and
`getsockname' to set and examine a socket's address.  These functions
use a phony data type, `struct sockaddr *', to accept the address.  In
practice, the address lives in a structure of some other data type
appropriate to the address format you are using, but you cast its
address to `struct sockaddr *' when you pass it to `bind'.

Address Formats
---------------

   The functions `bind' and `getsockname' use the generic data type
`struct sockaddr *' to represent a pointer to a socket address.  You
can't use this data type effectively to interpret an address or
construct one; for that, you must use the proper data type for the
socket's namespace.

   Thus, the usual practice is to construct an address in the proper
namespace-specific type, then cast a pointer to `struct sockaddr *'
when you call `bind' or `getsockname'.

   The one piece of information that you can get from the `struct
sockaddr' data type is the "address format" designator which tells you
which data type to use to understand the address fully.

   The symbols in this section are defined in the header file
`sys/socket.h'.

 - Date Type: struct sockaddr
     The `struct sockaddr' type itself has the following members:

    `short int sa_family'
          This is the code for the address format of this address.  It
          identifies the format of the data which follows.

    `char sa_data[14]'
          This is the actual socket address data, which is
          format-dependent.  Its length also depends on the format, and
          may well be more than 14.  The length 14 of `sa_data' is
          essentially arbitrary.

   Each address format has a symbolic name which starts with `AF_'.
Each of them corresponds to a `PF_' symbol which designates the
corresponding namespace.  Here is a list of address format names:

`AF_FILE'
     This designates the address format that goes with the file
     namespace.  (`PF_FILE' is the name of that namespace.)  See File Namespace Details,
     for information about this address format.

`AF_UNIX'
     This is a synonym for `AF_FILE', for compatibility.  (`PF_UNIX' is
     likewise a synonym for `PF_FILE'.)

`AF_INET'
     This designates the address format that goes with the Internet
     namespace.  (`PF_INET' is the name of that namespace.) See
     Internet Address Format.

`AF_UNSPEC'
     This designates no particular address format.  It is used only in
     rare cases, such as to clear out the default destination address
     of a "connected" datagram socket.  See Sending Datagrams.

     The corresponding namespace designator symbol `PF_UNSPEC' exists
     for completeness, but there is no reason to use it in a program.

   `sys/socket.h' defines symbols starting with `AF_' for many
different kinds of networks, all or most of which are not actually
implemented.  We will document those that really work, as we receive
information about how to use them.

Setting the Address of a Socket
-------------------------------

   Use the `bind' function to assign an address to a socket.  The
prototype for `bind' is in the header file `sys/socket.h'.  For
examples of use, see File Namespace, or see Inet Example.

 - Function: int bind (int SOCKET, struct sockaddr *ADDR, size_t LENGTH)
     The `bind' function assigns an address to the socket SOCKET.  The
     ADDR and LENGTH arguments specify the address; the detailed format
     of the address depends on the namespace.  The first part of the
     address is always the format designator, which specifies a
     namespace, and says that the address is in the format for that
     namespace.

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

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

    `ENOTSOCK'
          The descriptor SOCKET is not a socket.

    `EADDRNOTAVAIL'
          The specified address is not available on this machine.

    `EADDRINUSE'
          Some other socket is already using the specified address.

    `EINVAL'
          The socket SOCKET already has an address.

    `EACCES'
          You do not have permission to access the requested address.
          (In the Internet domain, only the super-user is allowed to
          specify a port number in the range 0 through
          `IPPORT_RESERVED' minus one; see Ports.)

     Additional conditions may be possible depending on the particular
     namespace of the socket.

Reading the Address of a Socket
-------------------------------

   Use the function `getsockname' to examine the address of an Internet
socket.  The prototype for this function is in the header file
`sys/socket.h'.

 - Function: int getsockname (int SOCKET, struct sockaddr *ADDR, size_t
          *LENGTH-PTR)
     The `getsockname' function returns information about the address
     of the socket SOCKET in the locations specified by the ADDR and
     LENGTH-PTR arguments.  Note that the LENGTH-PTR is a pointer; you
     should initialize it to be the allocation size of ADDR, and on
     return it contains the actual size of the address data.

     The format of the address data depends on the socket namespace.
     The length of the information is usually fixed for a given
     namespace, so normally you can know exactly how much space is
     needed and can provide that much.  The usual practice is to
     allocate a place for the value using the proper data type for the
     socket's namespace, then cast its address to `struct sockaddr *'
     to pass it to `getsockname'.

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

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

    `ENOTSOCK'
          The descriptor SOCKET is not a socket.

    `ENOBUFS'
          There are not enough internal buffers available for the
          operation.

   You can't read the address of a socket in the file namespace.  This
is consistent with the rest of the system; in general, there's no way to
find a file's name from a descriptor for that file.

The File Namespace
==================

   This section describes the details of the file namespace, whose
symbolic name (required when you create a socket) is `PF_FILE'.

File Namespace Concepts
-----------------------

   In the file namespace, socket addresses are file names.  You can
specify any file name you want as the address of the socket, but you
must have write permission on the directory containing it.  In order to
connect to a socket, you must have read permission for it.  It's common
to put these files in the `/tmp' directory.

   One peculiarity of the file namespace is that the name is only used
when opening the connection; once that is over with, the address is not
meaningful and may not exist.

   Another peculiarity is that you cannot connect to such a socket from
another machine-not even if the other machine shares the file system
which contains the name of the socket.  You can see the socket in a
directory listing, but connecting to it never succeeds.  Some programs
take advantage of this, such as by asking the client to send its own
process ID, and using the process IDs to distinguish between clients.
However, we recommend you not use this method in protocols you design,
as we might someday permit connections from other machines that mount
the same file systems.  Instead, send each new client an identifying
number if you want it to have one.

   After you close a socket in the file namespace, you should delete the
file name from the file system.  Use `unlink' or `remove' to do this;
see Deleting Files.

   The file namespace supports just one protocol for any communication
style; it is protocol number `0'.

Details of File Namespace
-------------------------

   To create a socket in the file namespace, use the constant `PF_FILE'
as the NAMESPACE argument to `socket' or `socketpair'.  This constant
is defined in `sys/socket.h'.

 - Macro: int PF_FILE
     This designates the file namespace, in which socket addresses are
     file names, and its associated family of protocols.

 - Macro: int PF_UNIX
     This is a synonym for `PF_FILE', for compatibility's sake.

   The structure for specifying socket names in the file namespace is
defined in the header file `sys/un.h':

 - Data Type: struct sockaddr_un
     This structure is used to specify file namespace socket addresses.
     It has the following members:

    `short int sun_family'
          This identifies the address family or format of the socket
          address.  You should store the value `AF_FILE' to designate
          the file namespace.  See Socket Addresses.

    `char sun_path[108]'
          This is the file name to use.

          *Incomplete:*  Why is 108 a magic number?  RMS suggests making
          this a zero-length array and tweaking the example following
          to use `alloca' to allocate an appropriate amount of storage
          based on the length of the filename.

   You should compute the LENGTH parameter for a socket address in the
file namespace as the sum of the size of the `sun_family' component and
the string length (*not* the allocation size!) of the file name string.