   This file documents the GNU C library.

   This is Edition 0.03, last updated 19 May 1993, of
`The GNU C Library Reference Manual', for Version 1.06 Beta.

   Copyright (C) 1993 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.

Testing the Type of a File
--------------------------

   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 type code,
which you can use to tell whether the file is a directory, whether it is
a socket, and so on.  For information about the access permission,
see Permission Bits.

   There are two predefined ways you can access the file type portion of
the file mode.  First of all, for each type of file, there is a
"predicate macro" which examines a file mode value and returns true or
false--is the file of that type, or not.  Secondly, you can mask out
the rest of the file mode to get just a file type code. You can compare
this against various constants for the supported file types.

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

   The following predicate macros test the type of a file, given the
value M which is the `st_mode' field returned by `stat' on that file:

 -- Macro: int S_ISDIR (mode_t M)
     This macro returns nonzero if the file is a directory.

 -- Macro: int S_ISCHR (mode_t M)
     This macro returns nonzero if the file is a character special file
     (a device like a terminal).

 -- Macro: int S_ISBLK (mode_t M)
     This macro returns nonzero if the file is a block special file (a
     device like a disk).

 -- Macro: int S_ISREG (mode_t M)
     This macro returns nonzero if the file is a regular file.

 -- Macro: int S_ISFIFO (mode_t M)
     This macro returns nonzero if the file is a FIFO special file, or a
     pipe.  See Pipes and FIFOs.

 -- Macro: int S_ISLNK (mode_t M)
     This macro returns nonzero if the file is a symbolic link. See
     Symbolic Links.

 -- Macro: int S_ISSOCK (mode_t M)
     This macro returns nonzero if the file is a socket.  See
     Sockets.

   An alterate non-POSIX method of testing the file type is supported
for compatibility with BSD.  The mode can be bitwise ANDed with
`S_IFMT' to extract the file type code, and compared to the appropriate
type code constant.  For example,

     S_ISCHR (MODE)

is equivalent to:

     ((MODE & S_IFMT) == S_IFCHR)

 -- Macro: int S_IFMT
     This is a bit mask used to extract the file type code portion of a
     mode value.

   These are the symbolic names for the different file type codes:

`S_IFDIR'
     This macro represents the value of the file type code for a
     directory file.

`S_IFCHR'
     This macro represents the value of the file type code for a
     character-oriented device file.

`S_IFBLK'
     This macro represents the value of the file type code for a
     block-oriented device file.

`S_IFREG'
     This macro represents the value of the file type code for a
     regular file.

`S_IFLNK'
     This macro represents the value of the file type code for a
     symbolic link.

`S_IFSOCK'
     This macro represents the value of the file type code for a socket.

`S_IFIFO'
     This macro represents the value of the file type code for a FIFO
     or pipe.

File Owner
----------

   Every file has an "owner" which is one of the registered user names
defined on the system.  Each file also has a "group", which is one of
the defined groups.  The file owner can often be useful for showing you
who edited the file (especially when you edit with GNU Emacs), but its
main purpose is for access control.

   The file owner and group play a role in determining access because
the file has one set of access permission bits for the user that is the
owner, another set that apply to users who belong to the file's group,
and a third set of bits that apply to everyone else.  See Access Permission,
for the details of how access is decided based on this
data.

   When a file is created, its owner is set from the effective user ID
of the process that creates it (see Process Persona.).  The file's
group ID may be set from either effective group ID of the process, or
the group ID of the directory that contains the file, depending on the
system where the file is stored.  When you access a remote file system,
it behaves according to its own rule, not according to the system your
program is running on.  Thus, your program must be prepared to encounter
either kind of behavior, no matter what kind of system you run it on.

   You can change the owner and/or group owner of an existing file using
the `chown' function.  This is the primitive for the `chown' and
`chgrp' shell commands.

   The prototype for this function is declared in `unistd.h'.

 -- Function: int chown (const char *FILENAME, uid_t OWNER, gid_t GROUP)
     The `chown' function changes the owner of the file FILENAME to
     OWNER, and its group owner to GROUP.

     Changing the owner of the file on certain systems clears the
     set-user-ID and set-group-ID bits of the file's permissions.
     (This is because those bits may not be appropriate for the new
     owner.)  The other file permission bits are not changed.

     The return value is `0' on success 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:

    `EPERM'
          This process lacks permission to make the requested change.

          Only privileged users or the file's owner can change the
          file's group. On most file systems, only privileged users can
          change the file owner; some file systems allow you to change
          the owner if you are currently the owner.  When you access a
          remote file system, the behavior you encounter is determined
          by the system that actually holds the file, not by the system
          your program is running on.

          See Options for Files, for information about the
          `_POSIX_CHOWN_RESTRICTED' macro.

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

 -- Function: int fchown (int FILEDES, int OWNER, int GROUP)
     This is like `chown', except that it changes the owner of the file
     with open file descriptor FILEDES.

     The return value from `fchown' 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, not an
          ordinary file.

    `EPERM'
          This process lacks permission to make the requested change.
          For details, see `chmod', above.

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

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. See
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. See How Change Persona.

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

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

     On an executable file, it modifies the swapping policies of the
     system. Normally, when a program terminates, its pages in core are
     immediately freed and reused.  If the sticky bit is set on the
     executable file, the system keeps the pages in core for a while as
     if the program were still running.  This is advantageous for a
     program that is likely to be run many times in succession.

     On a directory, the sticky bit gives permission to delete a file
     in the directory if you can write the contents of 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 sticky bit makes it
     possible to control deletion for individual files.

   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 nonportable, it also requires everyone who
reads your program to remember what the bits mean.  To make your
program clean, use the symbolic names.

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

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.  There is actually no way to set the mode of a link,
     which is always `-1'.

     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.

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

   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.

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.

   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); others 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 next 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
     acceptible 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 is also format-dependent, 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 a Socket's Address
--------------------------

   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.

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