@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC128Št�”›Low-Level Input/Output

@�”˜This chapter describes functions for performing low-level input/output operations on file descriptors. These functions include the primitives for the higher-level I/O functions described in section ‰ŠP�”›Input/Output on Streams@�”˜, as well as functions for performing low-level control operations for which there are no equivalents on streams.
Stream-level I/O is more flexible and usually more convenient; therefore, programmers generally use the descriptor-level functions only when necessary. These are some of the usual reasons: þÂ
• For reading binary files in large chunks.
• For reading an entire file into core before parsing it.
• To perform operations other than data transfer, which can only be done with a descriptor. (You can use Hfileno@ to get the descriptor corresponding to a stream.)
• To pass descriptors to a child process. (The child can create its own stream to use a descriptor that it inherits, but cannot inherit a stream directly.)Àð
ˆ‰SEC129Št�”›Opening and Closing Files

‰IDX605Š‰IDX606Š@�”˜This section describes the primitives for opening and closing files using file descriptors. The Hopen@ and Hcreat@ functions are declared in the header file H`fcntl.h'@, while Hclose@ is declared in H`unistd.h'@. ‰IDX607Š‰IDX608Š

A�”˜Function:@ int Dopen@ B(const char *Bfilename@, int Bflags@[, mode_t Bmode@])
Â‰IDX609Š@�”˜The Hopen@ function creates and returns a new file descriptor for the file named by Bfilename@. Initially, the file position indicator for the file is at the beginning of the file. The argument Bmode@ is used only when a file is created, but it doesn't hurt to supply the argument in any case.
The Bflags@ argument controls how the file is to be opened. This is a bit mask; you create the value by the bitwise OR of the appropriate parameters (using the H`|'@ operator in C). See section ‰ŠP�”›File Status Flags@�”˜, for the parameters available.
The normal return value from Hopen@ is a non-negative integer file descriptor. In the case of an error, a value of H-1@ is returned instead. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@The file exists but is not readable/writable as requested by the Bflags@ argument, the file does not exist and the directory is unwritable so it cannot be created.
ÂHEEXIST
Ä@Both HO_CREAT@ and HO_EXCL@ are set, and the named file already exists.
ÂHEINTR
Ä@The Hopen@ operation was interrupted by a signal. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜.
ÂHEISDIR
Ä@The Bflags@ argument specified write access, and the file is a directory.
ÂHEMFILE
Ä@The process has too many files open. The maximum number of file descriptors is controlled by the HRLIMIT_NOFILE@ resource limit; see section ‰ŠP�”›Limiting Resource Usage@�”˜.
ÂHENFILE
Ä@The entire system, or perhaps the file system which contains the directory, cannot support any additional open files at the moment. (This problem cannot happen on the GNU system.)
ÂHENOENT
Ä@The named file does not exist, and HO_CREAT@ is not specified.
ÂHENOSPC
Ä@The directory or file system that would contain the new file cannot be extended, because there is no disk space left.
ÂHENXIO
ÄHO_NONBLOCK@ and HO_WRONLY@ are both set in the Bflags@ argument, the file named by Bfilename@ is a FIFO (see section ‰ŠP�”›Pipes and FIFOs@�”˜), and no process has the file open for reading.
ÂHEROFS
Ä@The file resides on a read-only file system and any of HO_WRONLY@, HO_RDWR@, and HO_TRUNC@ are set in the Bflags@ argument, or HO_CREAT@ is set and the file does not already exist.Â

The Hopen@ function is the underlying primitive for the Hfopen@ and Hfreopen@ functions, that create streams.À

AObsolete function:@ int Dcreat@ B(const char *Bfilename@, mode_t Bmode@)
Â‰IDX610Š@�”˜This function is obsolete. The call: creat (Bfilename@, Bmode@)
is equivalent to: open (Bfilename@, O_WRONLY | O_CREAT | O_TRUNC, Bmode@) À

AFunction:@ int Dclose@ B(int Bfiledes@)
Â‰IDX611Š@�”˜The function Hclose@ closes the file descriptor Bfiledes@. Closing a file has the following consequences: þÄ
• The file descriptor is deallocated.
• Any record locks owned by the process on the file are unlocked.
• When all file descriptors associated with a pipe or FIFO have been closed, any unread data is discarded.Âð
The normal return value from Hclose@ is H0@; a value of H-1@ is returned in case of failure. The following Herrno@ error conditions are defined for this function:
HEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor.
ÂHEINTR
Ä@The Hclose@ call was interrupted by a signal. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜. Here is an example of how to handle HEINTR@ properly: TEMP_FAILURE_RETRY (close (desc));
ÂHENOSPC
Ä
ÂHEIO
Ä
ÂHEDQUOT
Ä@When the file is accessed by NFS, these errors from Hwrite@ can sometimes not be detected until Hclose@. See section ‰ŠP�”›Input and Output Primitives@�”˜, for details on their meaning.Â
À

To close a stream, call Hfclose@ (see section ‰ŠP�”›Closing Streams@�”˜) instead of trying to close its underlying file descriptor with Hclose@. This flushes any buffered output and updates the stream object to indicate that it is closed.
ˆ‰SEC130Št�”›Input and Output Primitives

@�”˜This section describes the functions for performing primitive input and output operations on file descriptors: Hread@, Hwrite@, and Hlseek@. These functions are declared in the header file H`unistd.h'@. ‰IDX612Š

A�”˜Data Type:@ Dssize_t
Â‰IDX613Š@�”˜This data type is used to represent the sizes of blocks that can be read or written in a single operation. It is similar to Hsize_t@, but must be a signed type.À

‰IDX614Š
A�”˜Function:@ ssize_t Dread@ B(int Bfiledes@, void *Bbuffer@, size_t Bsize@)
Â‰IDX615Š@�”˜The Hread@ function reads up to Bsize@ bytes from the file with descriptor Bfiledes@, storing the results in the Bbuffer@. (This is not necessarily a character string and there is no terminating null character added.)
‰IDX616Š@�”˜The return value is the number of bytes actually read. This might be less than Bsize@; for example, if there aren't that many bytes left in the file or if there aren't that many bytes immediately available. The exact behavior depends on what kind of file it is. Note that reading less than Bsize@ bytes is not an error.
A value of zero indicates end-of-file (except if the value of the Bsize@ argument is also zero). This is not considered an error. If you keep calling Hread@ while at end-of-file, it will keep returning zero and doing nothing else.
If Hread@ returns at least one character, there is no way you can tell whether end-of-file was reached. But if you did reach the end, the next read will return zero.
In case of an error, Hread@ returns H-1@. The following Herrno@ error conditions are defined for this function:
HEAGAIN
Ä@Normally, when no input is immediately available, Hread@ waits for some input. But if the HO_NONBLOCK@ flag is set for the file (see section ‰ŠP�”›File Status Flags@�”˜), Hread@ returns immediately without reading any data, and reports this error. DCompatibility Note:@ Most versions of BSD Unix use a different error code for this: HEWOULDBLOCK@. In the GNU library, HEWOULDBLOCK@ is an alias for HEAGAIN@, so it doesn't matter which name you use. On some systems, reading a large amount of data from a character special file can also fail with HEAGAIN@ if the kernel cannot find enough physical memory to lock down the user's pages. This is limited to devices that transfer with direct memory access into the user's memory, which means it does not include terminals, since they always use separate buffers inside the kernel. This problem never happens in the GNU system. Any condition that could result in HEAGAIN@ can instead result in a successful Hread@ which returns fewer bytes than requested. Calling Hread@ again immediately would result in HEAGAIN@.
ÂHEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor, or is not open for reading.
ÂHEINTR
ÄHread@ was interrupted by a signal while it was waiting for input. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜. A signal will not necessary cause Hread@ to return HEINTR@; it may instead result in a successful Hread@ which returns fewer bytes than requested.
ÂHEIO
Ä@For many devices, and for disk files, this error code indicates a hardware error. HEIO@ also occurs when a background process tries to read from the controlling terminal, and the normal action of stopping the process by sending it a HSIGTTIN@ signal isn't working. This might happen if signal is being blocked or ignored, or because the process group is orphaned. See section ‰ŠP�”›Job Control@�”˜, for more information about job control, and section ‰ŠP�”›Signal Handling@�”˜, for information about signals.Â

The Hread@ function is the underlying primitive for all of the functions that read from streams, such as Hfgetc@.À

‰IDX617Š
A�”˜Function:@ ssize_t Dwrite@ B(int Bfiledes@, const void *Bbuffer@, size_t Bsize@)
Â‰IDX618Š@�”˜The Hwrite@ function writes up to Bsize@ bytes from Bbuffer@ to the file with descriptor Bfiledes@. The data in Bbuffer@ is not necessarily a character string and a null character is output like any other character.
The return value is the number of bytes actually written. This may be Bsize@, but can always be smaller. Your program should always call Hwrite@ in a loop, iterating until all the data is written.
Once Hwrite@ returns, the data is enqueued to be written and can be read back right away, but it is not necessarily written out to permanent storage immediately. You can use Hfsync@ when you need to be sure your data has been permanently stored before continuing. (It is more efficient for the system to batch up consecutive writes and do them all at once when convenient. Normally they will always be written to disk within a minute or less.) You can use the HO_FSYNC@ open mode to make Hwrite@ always store the data to disk before returning; see section ‰ŠP�”›I/O Operating Modes@�”˜.
In the case of an error, Hwrite@ returns H-1@. The following Herrno@ error conditions are defined for this function:
HEAGAIN
Ä@Normally, Hwrite@ blocks until the write operation is complete. But if the HO_NONBLOCK@ flag is set for the file (see section ‰ŠP�”›Control Operations on Files@�”˜), it returns immediately without writing any data, and reports this error. An example of a situation that might cause the process to block on output is writing to a terminal device that supports flow control, where output has been suspended by receipt of a STOP character. DCompatibility Note:@ Most versions of BSD Unix use a different error code for this: HEWOULDBLOCK@. In the GNU library, HEWOULDBLOCK@ is an alias for HEAGAIN@, so it doesn't matter which name you use. On some systems, writing a large amount of data from a character special file can also fail with HEAGAIN@ if the kernel cannot find enough physical memory to lock down the user's pages. This is limited to devices that transfer with direct memory access into the user's memory, which means it does not include terminals, since they always use separate buffers inside the kernel. This problem does not arise in the GNU system.
ÂHEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor, or is not open for writing.
ÂHEFBIG
Ä@The size of the file would become larger than the implementation can support.
ÂHEINTR
Ä@The Hwrite@ operation was interrupted by a signal while it was blocked waiting for completion. A signal will not necessary cause Hwrite@ to return HEINTR@; it may instead result in a successful Hwrite@ which writes fewer bytes than requested. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜.
ÂHEIO
Ä@For many devices, and for disk files, this error code indicates a hardware error.
ÂHENOSPC
Ä@The device containing the file is full.
ÂHEPIPE
Ä@This error is returned when you try to write to a pipe or FIFO that isn't open for reading by any process. When this happens, a HSIGPIPE@ signal is also sent to the process; see section ‰ŠP�”›Signal Handling@�”˜.Â

Unless you have arranged to prevent HEINTR@ failures, you should check Herrno@ after each failing call to Hwrite@, and if the error was HEINTR@, you should simply repeat the call. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜. The easy way to do this is with the macro HTEMP_FAILURE_RETRY@, as follows: nbytes = TEMP_FAILURE_RETRY (write (desc, buffer, count));
The Hwrite@ function is the underlying primitive for all of the functions that write to streams, such as Hfputc@.À

ˆ‰SEC131Št�”›Setting the File Position of a Descriptor

@�”˜Just as you can set the file position of a stream with Hfseek@, you can set the file position of a descriptor with Hlseek@. This specifies the position in the file for the next Hread@ or Hwrite@ operation. See section ‰ŠP�”›File Positioning@�”˜, for more information on the file position and what it means.
To read the current file position value from a descriptor, use Hlseek (JdescH, 0, SEEK_CUR)@.
‰IDX619Š‰IDX620Š‰IDX621Š
A�”˜Function:@ off_t Dlseek@ B(int Bfiledes@, off_t Boffset@, int Bwhence@)
Â‰IDX622Š@�”˜The Hlseek@ function is used to change the file position of the file with descriptor Bfiledes@.
The Bwhence@ argument specifies how the Boffset@ should be interpreted in the same way as for the Hfseek@ function, and must be one of the symbolic constants HSEEK_SET@, HSEEK_CUR@, or HSEEK_END@.
HSEEK_SET
Ä@Specifies that Bwhence@ is a count of characters from the beginning of the file.
ÂHSEEK_CUR
Ä@Specifies that Bwhence@ is a count of characters from the current file position. This count may be positive or negative.
ÂHSEEK_END
Ä@Specifies that Bwhence@ is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.@end table The return value from Hlseek@ is normally the resulting file position, measured in bytes from the beginning of the file. You can use this feature together with HSEEK_CUR@ to read the current file position. If you want to append to the file, setting the file position to the current end of file with HSEEK_END@ is not sufficient. Another process may write more data after you seek but before you write, extending the file so the position you write onto clobbers their data. Instead, use the HO_APPEND@ operating mode; see section ‰ŠP�”›I/O Operating Modes@�”˜. You can set the file position past the current end of the file. This does not by itself make the file longer; Hlseek@ never changes the file. But subsequent output at that position will extend the file. Characters between the previous end of file and the new position are filled with zeros. Extending the file in this way can create a "hole": the blocks of zeros are not actually allocated on disk, so the file takes up less space than it appears so; it is then called a "sparse file". ‰IDX623Š‰IDX624Š@�”˜If the file position cannot be changed, or the operation is in some way invalid, Hlseek@ returns a value of H-1@. The following Herrno@ error conditions are defined for this function:
HEBADF
Æ@The Bfiledes@ is not a valid file descriptor.
ÄHEINVAL
Æ@The Bwhence@ argument value is not valid, or the resulting file offset is not valid. A file offset is invalid.
ÄHESPIPE
Æ@The Bfiledes@ corresponds to an object that cannot be positioned, such as a pipe, FIFO or terminal device. (POSIX.1 specifies this error only for pipes and FIFOs, but in the GNU system, you always get HESPIPE@ if the object is not seekable.)Ä
The Hlseek@ function is the underlying primitive for the Hfseek@, Hftell@ and Hrewind@ functions, which operate on streams instead of file descriptors.Â
You can have multiple descriptors for the same file if you open the file more than once, or if you duplicate a descriptor with Hdup@. Descriptors that come from separate calls to Hopen@ have independent file positions; using Hlseek@ on one descriptor has no effect on the other. For example, {
int d1, d2;
char buf[4];
d1 = open ("foo", O_RDONLY);
d2 = open ("foo", O_RDONLY);
lseek (d1, 1024, SEEK_SET);
read (d2, buf, 4);
} will read the first four characters of the file H`foo'@. (The error-checking code necessary for a real program has been omitted here for brevity.) By contrast, descriptors made by duplication share a common file position with the original descriptor that was duplicated. Anything which alters the file position of one of the duplicates, including reading or writing data, affects all of them alike. Thus, for example, {
int d1, d2, d3;
char buf1[4], buf2[4];
d1 = open ("foo", O_RDONLY);
d2 = dup (d1);
d3 = dup (d2);
lseek (d3, 1024, SEEK_SET);
read (d1, buf1, 4);
read (d2, buf2, 4);
} will read four characters starting with the 1024'th character of H`foo'@, and then four more characters starting with the 1028'th character.
AData Type:@ Doff_t
Ä‰IDX625Š@�”˜This is an arithmetic data type used to represent file sizes. In the GNU system, this is equivalent to Hfpos_t@ or Hlong int@.Â
These aliases for the H`SEEK_...'@ constants exist for the sake of compatibility with older BSD systems. They are defined in two different header files: H`fcntl.h'@ and H`sys/file.h'@.
HL_SET
Ä@An alias for HSEEK_SET@.
ÂHL_INCR
Ä@An alias for HSEEK_CUR@.
ÂHL_XTND
Ä@An alias for HSEEK_END@.Â

ˆ‰SEC132Št�”›Descriptors and Streams

‰IDX626Š‰IDX627Š‰IDX628Š
@�”˜Given an open file descriptor, you can create a stream for it with the Hfdopen@ function. You can get the underlying file descriptor for an existing stream with the Hfileno@ function. These functions are declared in the header file H`stdio.h'@. ‰IDX629Š

A�”˜Function:@ FILE * Dfdopen@ B(int Bfiledes@, const char *Bopentype@)
Ä‰IDX630Š@�”˜The Hfdopen@ function returns a new stream for the file descriptor Bfiledes@.
The Bopentype@ argument is interpreted in the same way as for the Hfopen@ function (see section ‰ŠP�”›Opening Streams@�”˜), except that the H`b'@ option is not permitted; this is because GNU makes no distinction between text and binary files. Also, H"w"@ and H"w+"@ do not cause truncation of the file; these have affect only when opening a file, and in this case the file has already been opened. You must make sure that the Bopentype@ argument matches the actual mode of the open file descriptor.
The return value is the new stream. If the stream cannot be created (for example, if the modes for the file indicated by the file descriptor do not permit the access specified by the Bopentype@ argument), a null pointer is returned instead.
In some other systems, Hfdopen@ may fail to detect that the modes for file descriptor do not permit the access specified by Hopentype@. The GNU C library always checks for this.Â

For an example showing the use of the Hfdopen@ function, see section ‰ŠP�”›Creating a Pipe@�”˜.

AFunction:@ int Dfileno@ B(FILE *Bstream@)
Ä‰IDX631Š@�”˜This function returns the file descriptor associated with the stream Bstream@. If an error is detected (for example, if the Bstream@ is not valid) or if Bstream@ does not do I/O to a file, Hfileno@ returns H-1@.Â

‰IDX632Š‰IDX633Š@�”˜There are also symbolic constants defined in H`unistd.h'@ for the file descriptors belonging to the standard streams Hstdin@, Hstdout@, and Hstderr@; see section ‰ŠP�”›Standard Streams@�”˜. ‰IDX634Š
H�”˜STDIN_FILENO
Ä‰IDX635Š@�”˜This macro has value H0@, which is the file descriptor for standard input. ‰IDX636Š
ÂH�”˜STDOUT_FILENO
Ä‰IDX637Š@�”˜This macro has value H1@, which is the file descriptor for standard output. ‰IDX638Š
ÂH�”˜STDERR_FILENO
Ä‰IDX639Š@�”˜This macro has value H2@, which is the file descriptor for standard error output.Â

‰IDX640Š
ˆ‰SEC133Št�”›Dangers of Mixing Streams and Descriptors

‰IDX641Š‰IDX642Š‰IDX643Š‰IDX644Š
@�”˜You can have multiple file descriptors and streams (let's call both streams and descriptors "channels" for short) connected to the same file, but you must take care to avoid confusion between channels. There are two cases to consider: Blinked@ channels that share a single file position value, and Bindependent@ channels that have their own file positions.
It's best to use just one channel in your program for actual data transfer to any given file, except when all the access is for input. For example, if you open a pipe (something you can only do at the file descriptor level), either do all I/O with the descriptor, or construct a stream from the descriptor with Hfdopen@ and then do all I/O with the stream.
ˆ‰SEC134ŠT�”›Linked Channels

‰IDX645Š
@�”˜Channels that come from a single opening share the same file position; we call them Blinked@ channels. Linked channels result when you make a stream from a descriptor using Hfdopen@, when you get a descriptor from a stream with Hfileno@, when you copy a descriptor with Hdup@ or Hdup2@, and when descriptors are inherited during Hfork@. For files that don't support random access, such as terminals and pipes, Ball@ channels are effectively linked. On random-access files, all append-type output streams are effectively linked to each other.
‰IDX646Š@�”˜If you have been using a stream for I/O, and you want to do I/O using another channel (either a stream or a descriptor) that is linked to it, you must first Bclean up@ the stream that you have been using. See section ‰ŠP�”›Cleaning Streams@�”˜.
Terminating a process, or executing a new program in the process, destroys all the streams in the process. If descriptors linked to these streams persist in other processes, their file positions become undefined as a result. To prevent this, you must clean up the streams before destroying them.
ˆ‰SEC135ŠT�”›Independent Channels

‰IDX647Š
@�”˜When you open channels (streams or descriptors) separately on a seekable file, each channel has its own file position. These are called Bindependent channels@.
The system handles each channel independently. Most of the time, this is quite predictable and natural (especially for input): each channel can read or write sequentially at its own place in the file. However, if some of the channels are streams, you must take these precautions: þÄ
• You should clean an output stream after use, before doing anything else that might read or write from the same part of the file.
• You should clean an input stream before reading data that may have been modified using an independent channel. Otherwise, you might read obsolete data that had been in the stream's buffer.Âð
If you do output to one channel at the end of the file, this will certainly leave the other independent channels positioned somewhere before the new end. You cannot reliably set their file positions to the new end of file before writing, because the file can always be extended by another process between when you set the file position and when you write the data. Instead, use an append-type descriptor or stream; they always output at the current end of the file. In order to make the end-of-file position accurate, you must clean the output channel you were using, if it is a stream.
It's impossible for two channels to have separate file pointers for a file that doesn't support random access. Thus, channels for reading or writing such files are always linked, never independent. Append-type channels are also always linked. For these channels, follow the rules for linked channels; see section ‰ŠP�”›Linked Channels@�”˜.
ˆ‰SEC136ŠT�”›Cleaning Streams

@�”˜On the GNU system, you can clean up any stream with Hfclean@:

AFunction:@ int Dfclean@ B(FILE *Bstream@)
Ä‰IDX648Š@�”˜Clean up the stream Bstream@ so that its buffer is empty. If Bstream@ is doing output, force it out. If Bstream@ is doing input, give the data in the buffer back to the system, arranging to reread it.Â

On other systems, you can use Hfflush@ to clean a stream in most cases.
You can skip the Hfclean@ or Hfflush@ if you know the stream is already clean. A stream is clean whenever its buffer is empty. For example, an unbuffered stream is always clean. An input stream that is at end-of-file is clean. A line-buffered stream is clean when the last character output was a newline.
There is one case in which cleaning a stream is impossible on most systems. This is when the stream is doing input from a file that is not random-access. Such streams typically read ahead, and when the file is not random access, there is no way to give back the excess data already read. When an input stream reads from a random-access file, Hfflush@ does clean the stream, but leaves the file pointer at an unpredictable place; you must set the file pointer before doing any further I/O. On the GNU system, using Hfclean@ avoids both of these problems.
Closing an output-only stream also does Hfflush@, so this is a valid way of cleaning an output stream. On the GNU system, closing an input stream does Hfclean@.
You need not clean a stream before using its descriptor for control operations such as setting terminal modes; these operations don't affect the file position and are not affected by it. You can use any descriptor for these operations, and all channels are affected simultaneously. However, text already "output" to a stream but still buffered by the stream will be subject to the new terminal modes when subsequently flushed. To make sure "past" output is covered by the terminal settings that were in effect at the time, flush the output streams for that terminal before setting the modes. See section ‰ŠP�”›Terminal Modes@�”˜.
ˆ‰SEC137Št�”›Waiting for Input or Output

‰IDX649Š‰IDX650Š‰IDX651Š
@�”˜Sometimes a program needs to accept input on multiple input channels whenever input arrives. For example, some workstations may have devices such as a digitizing tablet, function button box, or dial box that are connected via normal asynchronous serial interfaces; good user interface style requires responding immediately to input on any device. Another example is a program that acts as a server to several other processes via pipes or sockets.
You cannot normally use Hread@ for this purpose, because this blocks the program until input is available on one particular file descriptor; input on other channels won't wake it up. You could set nonblocking mode and poll each file descriptor in turn, but this is very inefficient.
A better solution is to use the Hselect@ function. This blocks the program until input or output is ready on a specified set of file descriptors, or until a timer expires, whichever comes first. This facility is declared in the header file H`sys/types.h'@. ‰IDX652Š
@�”˜In the case of a server socket (see section ‰ŠP�”›Listening for Connections@�”˜), we say that "input" is available when there are pending connections that could be accepted (see section ‰ŠP�”›Accepting Connections@�”˜). Haccept@ for server sockets blocks and interacts with Hselect@ just as Hread@ does for normal input.
‰IDX653Š@�”˜The file descriptor sets for the Hselect@ function are specified as Hfd_set@ objects. Here is the description of the data type and some macros for manipulating these objects.

AData Type:@ Dfd_set
Ä‰IDX654Š@�”˜The Hfd_set@ data type represents file descriptor sets for the Hselect@ function. It is actually a bit array.Â

AMacro:@ int DFD_SETSIZE
Ä‰IDX655Š@�”˜The value of this macro is the maximum number of file descriptors that a Hfd_set@ object can hold information about. On systems with a fixed maximum number, HFD_SETSIZE@ is at least that number. On some systems, including GNU, there is no absolute limit on the number of descriptors open, but this macro still has a constant value which controls the number of bits in an Hfd_set@; if you get a file descriptor with a value as high as HFD_SETSIZE@, you cannot put that descriptor into an Hfd_set@.Â

AMacro:@ void DFD_ZERO@ B(fd_set *Bset@)
Ä‰IDX656Š@�”˜This macro initializes the file descriptor set Bset@ to be the empty set.Â

AMacro:@ void DFD_SET@ B(int Bfiledes@, fd_set *Bset@)
Ä‰IDX657Š@�”˜This macro adds Bfiledes@ to the file descriptor set Bset@.Â

AMacro:@ void DFD_CLR@ B(int Bfiledes@, fd_set *Bset@)
Ä‰IDX658Š@�”˜This macro removes Bfiledes@ from the file descriptor set Bset@.Â

AMacro:@ int DFD_ISSET@ B(int Bfiledes@, fd_set *Bset@)
Ä‰IDX659Š@�”˜This macro returns a nonzero value (true) if Bfiledes@ is a member of the the file descriptor set Bset@, and zero (false) otherwise.Â

Next, here is the description of the Hselect@ function itself.

AFunction:@ int Dselect@ B(int Bnfds@, fd_set *Bread-fds@, fd_set *Bwrite-fds@, fd_set *Bexcept-fds@, struct timeval *Btimeout@)
Ä‰IDX660Š@�”˜The Hselect@ function blocks the calling process until there is activity on any of the specified sets of file descriptors, or until the timeout period has expired.
The file descriptors specified by the Bread-fds@ argument are checked to see if they are ready for reading; the Bwrite-fds@ file descriptors are checked to see if they are ready for writing; and the Bexcept-fds@ file descriptors are checked for exceptional conditions. You can pass a null pointer for any of these arguments if you are not interested in checking for that kind of condition.
A file descriptor is considered ready for reading if it is at end of file. A server socket is considered ready for reading if there is a pending connection which can be accepted with Haccept@; see section ‰ŠP�”›Accepting Connections@�”˜. A client socket is ready for writing when its connection is fully established; see section ‰ŠP�”›Making a Connection@�”˜.
"Exceptional conditions" does not mean errors--errors are reported immediately when an erroneous system call is executed, and do not constitute a state of the descriptor. Rather, they include conditions such as the presence of an urgent message on a socket. (See section ‰ŠP�”›Sockets@�”˜, for information on urgent messages.)
The Hselect@ function checks only the first Bnfds@ file descriptors. The usual thing is to pass HFD_SETSIZE@ as the value of this argument.
The Btimeout@ specifies the maximum time to wait. If you pass a null pointer for this argument, it means to block indefinitely until one of the file descriptors is ready. Otherwise, you should provide the time in Hstruct timeval@ format; see section ‰ŠP�”›High-Resolution Calendar@�”˜. Specify zero as the time (a Hstruct timeval@ containing all zeros) if you want to find out which descriptors are ready without waiting if none are ready.
The normal return value from Hselect@ is the total number of ready file descriptors in all of the sets. Each of the argument sets is overwritten with information about the descriptors that are ready for the corresponding operation. Thus, to see if a particular descriptor Bdesc@ has input, use HFD_ISSET (JdescH, Jread-fdsH)@ after Hselect@ returns.
If Hselect@ returns because the timeout period expires, it returns a value of zero.
Any signal will cause Hselect@ to return immediately. So if your program uses signals, you can't rely on Hselect@ to keep waiting for the full time specified. If you want to be sure of waiting for a particular amount of time, you must check for HEINTR@ and repeat the Hselect@ with a newly calculated timeout based on the current time. See the example below. See also section ‰ŠP�”›Primitives Interrupted by Signals@�”˜.
If an error occurs, Hselect@ returns H-1@ and does not modify the argument file descriptor sets. The following Herrno@ error conditions are defined for this function:
HEBADF
Æ@One of the file descriptor sets specified an invalid file descriptor.
ÄHEINTR
Æ@The operation was interrupted by a signal. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜.
ÄHEINVAL
Æ@The Btimeout@ argument is invalid; one of the components is negative or too large.Ä
Â

DPortability Note:@ The Hselect@ function is a BSD Unix feature.
Here is an example showing how you can use Hselect@ to establish a timeout period for reading from a file descriptor. The Hinput_timeout@ function blocks the calling process until input is available on the file descriptor, or until the timeout period expires. #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>

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

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

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

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

int
main (void)
{
fprintf (stderr, "select returned %d.\n",
input_timeout (STDIN_FILENO, 5));
return 0;
}
There is another example showing the use of Hselect@ to multiplex input from multiple sockets in section ‰ŠP�”›Byte Stream Connection Server Example@�”˜.
ˆ‰SEC138Št�”›Control Operations on Files

‰IDX661Š‰IDX662Š@�”˜This section describes how you can perform various other operations on file descriptors, such as inquiring about or setting flags describing the status of the file descriptor, manipulating record locks, and the like. All of these operations are performed by the function Hfcntl@.
The second argument to the Hfcntl@ function is a command that specifies which operation to perform. The function and macros that name various flags that are used with it are declared in the header file H`fcntl.h'@. Many of these flags are also used by the Hopen@ function; see section ‰ŠP�”›Opening and Closing Files@�”˜. ‰IDX663Š

A�”˜Function:@ int Dfcntl@ B(int Bfiledes@, int Bcommand@, ...)
Ä‰IDX664Š@�”˜The Hfcntl@ function performs the operation specified by Bcommand@ on the file descriptor Bfiledes@. Some commands require additional arguments to be supplied. These additional arguments and the return value and error conditions are given in the detailed descriptions of the individual commands.
Briefly, here is a list of what the various commands are.
HF_DUPFD
Æ@Duplicate the file descriptor (return another file descriptor pointing to the same open file). See section ‰ŠP�”›Duplicating Descriptors@�”˜.
ÄHF_GETFD
Æ@Get flags associated with the file descriptor. See section ‰ŠP�”›File Descriptor Flags@�”˜.
ÄHF_SETFD
Æ@Set flags associated with the file descriptor. See section ‰ŠP�”›File Descriptor Flags@�”˜.
ÄHF_GETFL
Æ@Get flags associated with the open file. See section ‰ŠP�”›File Status Flags@�”˜.
ÄHF_SETFL
Æ@Set flags associated with the open file. See section ‰ŠP�”›File Status Flags@�”˜.
ÄHF_GETLK
Æ@Get a file lock. See section ‰ŠP�”›File Locks@�”˜.
ÄHF_SETLK
Æ@Set or clear a file lock. See section ‰ŠP�”›File Locks@�”˜.
ÄHF_SETLKW
Æ@Like HF_SETLK@, but wait for completion. See section ‰ŠP�”›File Locks@�”˜.
ÄHF_GETOWN
Æ@Get process or process group ID to receive HSIGIO@ signals. See section ‰ŠP�”›Interrupt-Driven Input@�”˜.
ÄHF_SETOWN
Æ@Set process or process group ID to receive HSIGIO@ signals. See section ‰ŠP�”›Interrupt-Driven Input@�”˜.Ä
Â

ˆ‰SEC139Št�”›Duplicating Descriptors

‰IDX665Š‰IDX666Š
@�”˜You can Bduplicate@ a file descriptor, or allocate another file descriptor that refers to the same open file as the original. Duplicate descriptors share one file position and one set of file status flags (see section ‰ŠP�”›File Status Flags@�”˜), but each has its own set of file descriptor flags (see section ‰ŠP�”›File Descriptor Flags@�”˜).
The major use of duplicating a file descriptor is to implement Bredirection@ of input or output: that is, to change the file or pipe that a particular file descriptor corresponds to.
You can perform this operation using the Hfcntl@ function with the HF_DUPFD@ command, but there are also convenient functions Hdup@ and Hdup2@ for duplicating descriptors.
‰IDX667Š‰IDX668Š@�”˜The Hfcntl@ function and flags are declared in H`fcntl.h'@, while prototypes for Hdup@ and Hdup2@ are in the header file H`unistd.h'@.

AFunction:@ int Ddup@ B(int Bold@)
Ä‰IDX669Š@�”˜This function copies descriptor Bold@ to the first available descriptor number (the first number not currently open). It is equivalent to Hfcntl (JoldH, F_DUPFD, 0)@.Â

AFunction:@ int Ddup2@ B(int Bold@, int Bnew@)
Ä‰IDX670Š@�”˜This function copies the descriptor Bold@ to descriptor number Bnew@.
If Bold@ is an invalid descriptor, then Hdup2@ does nothing; it does not close Bnew@. Otherwise, the new duplicate of Bold@ replaces any previous meaning of descriptor Bnew@, as if Bnew@ were closed first.
If Bold@ and Bnew@ are different numbers, and Bold@ is a valid descriptor number, then Hdup2@ is equivalent to: close (Bnew@);
fcntl (Bold@, F_DUPFD, Bnew@)
However, Hdup2@ does this atomically; there is no instant in the middle of calling Hdup2@ at which Bnew@ is closed and not yet a duplicate of Bold@.Â

AMacro:@ int DF_DUPFD
Ä‰IDX671Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to copy the file descriptor given as the first argument.
The form of the call in this case is: fcntl (Bold@, F_DUPFD, Bnext-filedes@)
The Bnext-filedes@ argument is of type Hint@ and specifies that the file descriptor returned should be the next available one greater than or equal to this value.
The return value from Hfcntl@ with this command is normally the value of the new file descriptor. A return value of H-1@ indicates an error. The following Herrno@ error conditions are defined for this command:
HEBADF
Æ@The Bold@ argument is invalid.
ÄHEINVAL
Æ@The Bnext-filedes@ argument is invalid.
ÄHEMFILE
Æ@There are no more file descriptors available--your program is already using the maximum. In BSD and GNU, the maximum is controlled by a resource limit that can be changed; see section ‰ŠP�”›Limiting Resource Usage@�”˜, for more information about the HRLIMIT_NOFILE@ limit.Ä

HENFILE@ is not a possible error code for Hdup2@ because Hdup2@ does not create a new opening of a file; duplicate descriptors do not count toward the limit which HENFILE@ indicates. HEMFILE@ is possible because it refers to the limit on distinct descriptor numbers in use in one process.Â

Here is an example showing how to use Hdup2@ to do redirection. Typically, redirection of the standard streams (like Hstdin@) is done by a shell or shell-like program before calling one of the Hexec@ functions (see section ‰ŠP�”›Executing a File@�”˜) to execute a new program in a child process. When the new program is executed, it creates and initializes the standard streams to point to the corresponding file descriptors, before its Hmain@ function is invoked.
So, to redirect standard input to a file, the shell could do something like: pid = fork ();
if (pid == 0)
{
char *filename;
char *program;
int file;
...
file = TEMP_FAILURE_RETRY (open (filename, O_RDONLY));
dup2 (file, STDIN_FILENO);
TEMP_FAILURE_RETRY (close (file));
execv (program, NULL);
}
There is also a more detailed example showing how to implement redirection in the context of a pipeline of processes in section ‰ŠP�”›Launching Jobs@�”˜.
ˆ‰SEC140Št�”›File Descriptor Flags

‰IDX672Š
B�”˜File descriptor flags@ are miscellaneous attributes of a file descriptor. These flags are associated with particular file descriptors, so that if you have created duplicate file descriptors from a single opening of a file, each descriptor has its own set of flags.
Currently there is just one file descriptor flag: HFD_CLOEXEC@, which causes the descriptor to be closed if you use any of the Hexec...@ functions (see section ‰ŠP�”›Executing a File@�”˜).
The symbols in this section are defined in the header file H`fcntl.h'@. ‰IDX673Š

A�”˜Macro:@ int DF_GETFD
Ä‰IDX674Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should return the file descriptor flags associated with the Bfiledes@ argument.
The normal return value from Hfcntl@ with this command is a nonnegative number which can be interpreted as the bitwise OR of the individual flags (except that currently there is only one flag to use).
In case of an error, Hfcntl@ returns H-1@. The following Herrno@ error conditions are defined for this command:
HEBADF
Æ@The Bfiledes@ argument is invalid.Ä
Â

AMacro:@ int DF_SETFD
Ä‰IDX675Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should set the file descriptor flags associated with the Bfiledes@ argument. This requires a third Hint@ argument to specify the new flags, so the form of the call is: fcntl (Bfiledes@, F_SETFD, Bnew-flags@)
The normal return value from Hfcntl@ with this command is an unspecified value other than H-1@, which indicates an error. The flags and error conditions are the same as for the HF_GETFD@ command.Â

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

AMacro:@ int DFD_CLOEXEC
Ä‰IDX676Š‰IDX677Š@�”˜This flag specifies that the file descriptor should be closed when an Hexec@ function is invoked; see section ‰ŠP�”›Executing a File@�”˜. When a file descriptor is allocated (as with Hopen@ or Hdup@), this bit is initially cleared on the new file descriptor, meaning that descriptor will survive into the new program after Hexec@.Â

If you want to modify the file descriptor flags, you should get the current flags with HF_GETFD@ and modify the value. Don't assume that the flags listed here are the only ones that are implemented; your program may be run years from now and more flags may exist then. For example, here is a function to set or clear the flag HFD_CLOEXEC@ without altering any other flags: /* Set the HFD_CLOEXEC@ flag of Bdesc@ if Bvalue@ is nonzero,
or clear the flag if Bvalue@ is 0.
Return 0 on success, or -1 on error with Herrno@ set. */

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

‰IDX678Š
B�”˜File status flags@ are used to specify attributes of the opening of a file. Unlike the file descriptor flags discussed in section ‰ŠP�”›File Descriptor Flags@�”˜, the file status flags are shared by duplicated file descriptors resulting from a single opening of the file. The file status flags are specified with the Bflags@ argument to Hopen@; see section ‰ŠP�”›Opening and Closing Files@�”˜.
File status flags fall into three categories, which are described in the following sections. þÄ
• section ‰ŠP�”›File Access Modes@�”˜, specify what type of access is allowed to the file: reading, writing, or both. They are set by Hopen@ and are returned by Hfcntl@, but cannot be changed.
• section ‰ŠP�”›Open-time Flags@�”˜, control details of what Hopen@ will do. These flags are not preserved after the Hopen@ call.
• section ‰ŠP�”›I/O Operating Modes@�”˜, affect how operations such as Hread@ and Hwrite@ are done. They are set by Hopen@, and can be fetched or changed with Hfcntl@.Âð
The symbols in this section are defined in the header file H`fcntl.h'@. ‰IDX679Š
ˆ‰SEC142ŠT�”›File Access Modes

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

AMacro:@ int DO_RDONLY
Ä‰IDX680Š@�”˜Open the file for read access.Â

AMacro:@ int DO_WRONLY
Ä‰IDX681Š@�”˜Open the file for write access.Â

AMacro:@ int DO_RDWR
Ä‰IDX682Š@�”˜Open the file for both reading and writing.Â

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

AMacro:@ int DO_READ
Ä‰IDX683Š@�”˜Open the file for reading. Same as HO_RDWR@; only defined on GNU.Â

AMacro:@ int DO_WRITE
Ä‰IDX684Š@�”˜Open the file for reading. Same as HO_WRONLY@; only defined on GNU.Â

AMacro:@ int DO_EXEC
Ä‰IDX685Š@�”˜Open the file for executing. Only defined on GNU.Â

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

AMacro:@ int DO_ACCMODE
Ä‰IDX686Š@�”˜This macro stands for a mask that can be bitwise-ANDed with the file status flag value to produce a value representing the file access mode. The mode will be HO_RDONLY@, HO_WRONLY@, or HO_RDWR@. (In the GNU system it could also be zero, and it never includes the HO_EXEC@ bit.)Â

ˆ‰SEC143ŠT�”›Open-time Flags

@�”˜The open-time flags specify options affecting how Hopen@ will behave. These options are not preserved once the file is open. The exception to this is HO_NONBLOCK@, which is also an I/O operating mode and so it Bis@ saved. See section ‰ŠP�”›Opening and Closing Files@�”˜, for how to call Hopen@.
There are two sorts of options specified by open-time flags. þÄ
• BFile name translation flags@ affect how Hopen@ looks up the file name to locate the file, and whether the file can be created. ‰IDX687Š‰IDX688Š
• B�”˜Open-time action flags@ specify extra operations that Hopen@ will perform on the file once it is open. ‰IDX689Š‰IDX690ŠÂð
@�”˜Here are the file name translation flags.

AMacro:@ int DO_CREAT
Ä‰IDX691Š@�”˜If set, the file will be created if it doesn't already exist. ‰IDX692ŠÂ

A�”˜Macro:@ int DO_EXCL
Ä‰IDX693Š@�”˜If both HO_CREAT@ and HO_EXCL@ are set, then Hopen@ fails if the specified file already exists. This is guaranteed to never clobber an existing file.Â

AMacro:@ int DO_NONBLOCK
Ä‰IDX694Š‰IDX695Š@�”˜This prevents Hopen@ from blocking for a "long time" to open the file. This is only meaningful for some kinds of files, usually devices such as serial ports; when it is not meaningful, it is harmless and ignored. Often opening a port to a modem blocks until the modem reports carrier detection; if HO_NONBLOCK@ is specified, Hopen@ will return immediately without a carrier.
Note that the HO_NONBLOCK@ flag is overloaded as both an I/O operating mode and a file name translation flag. This means that specifying HO_NONBLOCK@ in Hopen@ also sets nonblocking I/O mode; see section ‰ŠP�”›I/O Operating Modes@�”˜. To open the file without blocking but do normal I/O that blocks, you must call Hopen@ with HO_NONBLOCK@ set and then call Hfcntl@ to turn the bit off.Â

AMacro:@ int DO_NOCTTY
Ä‰IDX696Š@�”˜If the named file is a terminal device, don't make it the controlling terminal for the process. See section ‰ŠP�”›Job Control@�”˜, for information about what it means to be the controlling terminal.
In the GNU system and 4.4 BSD, opening a file never makes it the controlling terminal and HO_NOCTTY@ is zero. However, other systems may use a nonzero value for HO_NOCTTY@ and set the controlling terminal when you open a file that is a terminal device; so to be portable, use HO_NOCTTY@ when it is important to avoid this. ‰IDX697ŠÂ

@�”˜The following three file name translation flags exist only in the GNU system.

AMacro:@ int DO_IGNORE_CTTY
Ä‰IDX698Š@�”˜Do not recognize the named file as the controlling terminal, even if it refers to the process's existing controlling terminal device. Operations on the new file descriptor will never induce job control signals. See section ‰ŠP�”›Job Control@�”˜.Â

AMacro:@ int DO_NOLINK
Ä‰IDX699Š@�”˜If the named file is a symbolic link, open the link itself instead of the file it refers to. (Hfstat@ on the new file descriptor will return the information returned by Hlstat@ on the link's name.) ‰IDX700ŠÂ

A�”˜Macro:@ int DO_NOTRANS
Ä‰IDX701Š@�”˜If the named file is specially translated, do not invoke the translator. Open the bare file the translator itself sees.Â

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

AMacro:@ int DO_TRUNC
Ä‰IDX702Š@�”˜Truncate the file to zero length. This option is only useful for regular files, not special files such as directories or FIFOs. POSIX.1 requires that you open the file for writing to use HO_TRUNC@. In BSD and GNU you must have permission to write the file to truncate it, but you need not open for write access.
This is the only open-time action flag specified by POSIX.1. There is no good reason for truncation to be done by Hopen@, instead of by calling Hftruncate@ afterwards. The HO_TRUNC@ flag existed in Unix before Hftruncate@ was invented, and is retained for backward compatibility.Â

AMacro:@ int DO_SHLOCK
Ä‰IDX703Š@�”˜Acquire a shared lock on the file, as with Hflock@. See section ‰ŠP�”›File Locks@�”˜.
If HO_CREAT@ is specified, the locking is done atomically when creating the file. You are guaranteed that no other process will get the lock on the new file first.Â

AMacro:@ int DO_EXLOCK
Ä‰IDX704Š@�”˜Acquire an exclusive lock on the file, as with Hflock@. See section ‰ŠP�”›File Locks@�”˜. This is atomic like HO_SHLOCK@.Â

ˆ‰SEC144ŠT�”›I/O Operating Modes

@�”˜The operating modes affect how input and output operations using a file descriptor work. These flags are set by Hopen@ and can be fetched and changed with Hfcntl@.

AMacro:@ int DO_APPEND
Ä‰IDX705Š@�”˜The bit that enables append mode for the file. If set, then all Hwrite@ operations write the data at the end of the file, extending it, regardless of the current file position. This is the only reliable way to append to a file. In append mode, you are guaranteed that the data you write will always go to the current end of the file, regardless of other processes writing to the file. Conversely, if you simply set the file position to the end of file and write, then another process can extend the file after you set the file position but before you write, resulting in your data appearing someplace before the real end of file.Â

AMacro:@ int DO_NONBLOCK
Ä‰IDX706Š@�”˜The bit that enables nonblocking mode for the file. If this bit is set, Hread@ requests on the file can return immediately with a failure status if there is no input immediately available, instead of blocking. Likewise, Hwrite@ requests can also return immediately with a failure status if the output can't be written immediately.
Note that the HO_NONBLOCK@ flag is overloaded as both an I/O operating mode and a file name translation flag; see section ‰ŠP�”›Open-time Flags@�”˜.Â

AMacro:@ int DO_NDELAY
Ä‰IDX707Š@�”˜This is an obsolete name for HO_NONBLOCK@, provided for compatibility with BSD. It is not defined by the POSIX.1 standard.Â

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

AMacro:@ int DO_ASYNC
Ä‰IDX708Š@�”˜The bit that enables asynchronous input mode. If set, then HSIGIO@ signals will be generated when input is available. See section ‰ŠP�”›Interrupt-Driven Input@�”˜.
Asynchronous input mode is a BSD feature.Â

AMacro:@ int DO_FSYNC
Ä‰IDX709Š@�”˜The bit that enables synchronous writing for the file. If set, each Hwrite@ call will make sure the data is reliably stored on disk before returning.
Synchronous writing is a BSD feature.Â

AMacro:@ int DO_SYNC
Ä‰IDX710Š@�”˜This is another name for HO_FSYNC@. They have the same value.Â

AMacro:@ int DO_NOATIME
Ä‰IDX711Š@�”˜If this bit is set, Hread@ will not update the access time of the file. See section ‰ŠP�”›File Times@�”˜. This is used by programs that do backups, so that backing a file up does not count as reading it. Only the owner of the file or the superuser may use this bit.
This is a GNU extension.Â

ˆ‰SEC145ŠT�”›Getting and Setting File Status Flags

@�”˜The Hfcntl@ function can fetch or change file status flags.

AMacro:@ int DF_GETFL
Ä‰IDX712Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to read the file status flags for the open file with descriptor Bfiledes@.
The normal return value from Hfcntl@ with this command is a nonnegative number which can be interpreted as the bitwise OR of the individual flags. Since the file access modes are not single-bit values, you can mask off other bits in the returned flags with HO_ACCMODE@ to compare them.
In case of an error, Hfcntl@ returns H-1@. The following Herrno@ error conditions are defined for this command:
HEBADF
Æ@The Bfiledes@ argument is invalid.Ä
Â

AMacro:@ int DF_SETFL
Ä‰IDX713Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to set the file status flags for the open file corresponding to the Bfiledes@ argument. This command requires a third Hint@ argument to specify the new flags, so the call looks like this: fcntl (Bfiledes@, F_SETFL, Bnew-flags@)
You can't change the access mode for the file in this way; that is, whether the file descriptor was opened for reading or writing.
The normal return value from Hfcntl@ with this command is an unspecified value other than H-1@, which indicates an error. The error conditions are the same as for the HF_GETFL@ command.Â

If you want to modify the file status flags, you should get the current flags with HF_GETFL@ and modify the value. Don't assume that the flags listed here are the only ones that are implemented; your program may be run years from now and more flags may exist then. For example, here is a function to set or clear the flag HO_NONBLOCK@ without altering any other flags: /* Set the HO_NONBLOCK@ flag of Bdesc@ if Bvalue@ is nonzero,
or clear the flag if Bvalue@ is 0.
Return 0 on success, or -1 on error with Herrno@ set. */

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

‰IDX714Š‰IDX715Š@�”˜The remaining Hfcntl@ commands are used to support Brecord locking@, which permits multiple cooperating programs to prevent each other from simultaneously accessing parts of a file in error-prone ways.
‰IDX716Š‰IDX717Š@�”˜An Bexclusive@ or Bwrite@ lock gives a process exclusive access for writing to the specified part of the file. While a write lock is in place, no other process can lock that part of the file.
‰IDX718Š‰IDX719Š@�”˜A Bshared@ or Bread@ lock prohibits any other process from requesting a write lock on the specified part of the file. However, other processes can request read locks.
The Hread@ and Hwrite@ functions do not actually check to see whether there are any locks in place. If you want to implement a locking protocol for a file shared by multiple processes, your application must do explicit Hfcntl@ calls to request and clear locks at the appropriate points.
Locks are associated with processes. A process can only have one kind of lock set for each byte of a given file. When any file descriptor for that file is closed by the process, all of the locks that process holds on that file are released, even if the locks were made using other descriptors that remain open. Likewise, locks are released when a process exits, and are not inherited by child processes created using Hfork@ (see section ‰ŠP�”›Creating a Process@�”˜).
When making a lock, use a Hstruct flock@ to specify what kind of lock and where. This data type and the associated macros for the Hfcntl@ function are declared in the header file H`fcntl.h'@. ‰IDX720Š

A�”˜Data Type:@ Dstruct flock
Ä‰IDX721Š@�”˜This structure is used with the Hfcntl@ function to describe a file lock. It has these members:
Hshort int l_type
Æ@Specifies the type of the lock; one of HF_RDLCK@, HF_WRLCK@, or HF_UNLCK@.
ÄHshort int l_whence
Æ@This corresponds to the Bwhence@ argument to Hfseek@ or Hlseek@, and specifies what the offset is relative to. Its value can be one of HSEEK_SET@, HSEEK_CUR@, or HSEEK_END@.
ÄHoff_t l_start
Æ@This specifies the offset of the start of the region to which the lock applies, and is given in bytes relative to the point specified by Hl_whence@ member.
ÄHoff_t l_len
Æ@This specifies the length of the region to be locked. A value of H0@ is treated specially; it means the region extends to the end of the file.
ÄHpid_t l_pid
Æ@This field is the process ID (see section ‰ŠP�”›Process Creation Concepts@�”˜) of the process holding the lock. It is filled in by calling Hfcntl@ with the HF_GETLK@ command, but is ignored when making a lock.Ä
Â

AMacro:@ int DF_GETLK
Ä‰IDX722Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should get information about a lock. This command requires a third argument of type Hstruct flock *@ to be passed to Hfcntl@, so that the form of the call is: fcntl (Bfiledes@, F_GETLK, Blockp@)
If there is a lock already in place that would block the lock described by the Blockp@ argument, information about that lock overwrites H*Jlockp@. Existing locks are not reported if they are compatible with making a new lock as specified. Thus, you should specify a lock type of HF_WRLCK@ if you want to find out about both read and write locks, or HF_RDLCK@ if you want to find out about write locks only.
There might be more than one lock affecting the region specified by the Blockp@ argument, but Hfcntl@ only returns information about one of them. The Hl_whence@ member of the Blockp@ structure is set to HSEEK_SET@ and the Hl_start@ and Hl_len@ fields set to identify the locked region.
If no lock applies, the only change to the Blockp@ structure is to update the Hl_type@ to a value of HF_UNLCK@.
The normal return value from Hfcntl@ with this command is an unspecified value other than H-1@, which is reserved to indicate an error. The following Herrno@ error conditions are defined for this command:
HEBADF
Æ@The Bfiledes@ argument is invalid.
ÄHEINVAL
Æ@Either the Blockp@ argument doesn't specify valid lock information, or the file associated with Bfiledes@ doesn't support locks.Ä
Â

AMacro:@ int DF_SETLK
Ä‰IDX723Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should set or clear a lock. This command requires a third argument of type Hstruct flock *@ to be passed to Hfcntl@, so that the form of the call is: fcntl (Bfiledes@, F_SETLK, Blockp@)
If the process already has a lock on any part of the region, the old lock on that part is replaced with the new lock. You can remove a lock by specifying a lock type of HF_UNLCK@.
If the lock cannot be set, Hfcntl@ returns immediately with a value of H-1@. This function does not block waiting for other processes to release locks. If Hfcntl@ succeeds, it return a value other than H-1@.
The following Herrno@ error conditions are defined for this function:
HEAGAIN
Æ
ÄHEACCES
Æ@The lock cannot be set because it is blocked by an existing lock on the file. Some systems use HEAGAIN@ in this case, and other systems use HEACCES@; your program should treat them alike, after HF_SETLK@. (The GNU system always uses HEAGAIN@.)
ÄHEBADF
Æ@Either: the Bfiledes@ argument is invalid; you requested a read lock but the Bfiledes@ is not open for read access; or, you requested a write lock but the Bfiledes@ is not open for write access.
ÄHEINVAL
Æ@Either the Blockp@ argument doesn't specify valid lock information, or the file associated with Bfiledes@ doesn't support locks.
ÄHENOLCK
Æ@The system has run out of file lock resources; there are already too many file locks in place. Well-designed file systems never report this error, because they have no limitation on the number of locks. However, you must still take account of the possibility of this error, as it could result from network access to a file system on another machine.Ä
Â

AMacro:@ int DF_SETLKW
Ä‰IDX724Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should set or clear a lock. It is just like the HF_SETLK@ command, but causes the process to block (or wait) until the request can be specified.
This command requires a third argument of type Hstruct flock *@, as for the HF_SETLK@ command.
The Hfcntl@ return values and errors are the same as for the HF_SETLK@ command, but these additional Herrno@ error conditions are defined for this command:
HEINTR
Æ@The function was interrupted by a signal while it was waiting. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜.
ÄHEDEADLK
Æ@The specified region is being locked by another process. But that process is waiting to lock a region which the current process has locked, so waiting for the lock would result in deadlock. The system does not guarantee that it will detect all such conditions, but it lets you know if it notices one.Ä
Â

The following macros are defined for use as values for the Hl_type@ member of the Hflock@ structure. The values are integer constants.
HF_RDLCK
Ä‰IDX725Š@�”˜This macro is used to specify a read (or shared) lock. ‰IDX726Š
ÂH�”˜F_WRLCK
Ä@This macro is used to specify a write (or exclusive) lock. ‰IDX727Š
ÂH�”˜F_UNLCK
Ä@This macro is used to specify that the region is unlocked.Â

As an example of a situation where file locking is useful, consider a program that can be run simultaneously by several different users, that logs status information to a common file. One example of such a program might be a game that uses a file to keep track of high scores. Another example might be a program that records usage or accounting information for billing purposes.
Having multiple copies of the program simultaneously writing to the file could cause the contents of the file to become mixed up. But you can prevent this kind of problem by setting a write lock on the file before actually writing to the file.
If the program also needs to read the file and wants to make sure that the contents of the file are in a consistent state, then it can also use a read lock. While the read lock is set, no other process can lock that part of the file for writing.
Remember that file locks are only a Bvoluntary@ protocol for controlling access to a file. There is still potential for access to the file by programs that don't use the lock protocol.
ˆ‰SEC147Št�”›Interrupt-Driven Input

‰IDX728Š@�”˜If you set the HO_ASYNC@ status flag on a file descriptor (see section ‰ŠP�”›File Status Flags@�”˜), a HSIGIO@ signal is sent whenever input or output becomes possible on that file descriptor. The process or process group to receive the signal can be selected by using the HF_SETOWN@ command to the Hfcntl@ function. If the file descriptor is a socket, this also selects the recipient of HSIGURG@ signals that are delivered when out-of-band data arrives on that socket; see section ‰ŠP�”›Out-of-Band Data@�”˜. (HSIGURG@ is sent in any situation where Hselect@ would report the socket as having an "exceptional condition". See section ‰ŠP�”›Waiting for Input or Output@�”˜.)
If the file descriptor corresponds to a terminal device, then HSIGIO@ signals are sent to the foreground process group of the terminal. See section ‰ŠP�”›Job Control@�”˜.
‰IDX729Š@�”˜The symbols in this section are defined in the header file H`fcntl.h'@.

AMacro:@ int DF_GETOWN
Ä‰IDX730Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should get information about the process or process group to which HSIGIO@ signals are sent. (For a terminal, this is actually the foreground process group ID, which you can get using Htcgetpgrp@; see section ‰ŠP�”›Functions for Controlling Terminal Access@�”˜.)
The return value is interpreted as a process ID; if negative, its absolute value is the process group ID.
The following Herrno@ error condition is defined for this command:
HEBADF
Æ@The Bfiledes@ argument is invalid.Ä
Â

AMacro:@ int DF_SETOWN
Ä‰IDX731Š@�”˜This macro is used as the Bcommand@ argument to Hfcntl@, to specify that it should set the process or process group to which HSIGIO@ signals are sent. This command requires a third argument of type Hpid_t@ to be passed to Hfcntl@, so that the form of the call is: fcntl (Bfiledes@, F_SETOWN, Bpid@)
The Bpid@ argument should be a process ID. You can also pass a negative number whose absolute value is a process group ID.
The return value from Hfcntl@ with this command is H-1@ in case of error and some other value if successful. The following Herrno@ error conditions are defined for this command:
HEBADF
Æ@The Bfiledes@ argument is invalid.
ÄHESRCH
Æ@There is no process or process group corresponding to Bpid@.Ä
Â

Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.À