📄 llio.texi
字号:
@node Low-Level I/O, File System Interface, I/O on Streams, Top@chapter Low-Level Input/OutputThis chapter describes functions for performing low-level input/outputoperations on file descriptors. These functions include the primitivesfor the higher-level I/O functions described in @ref{I/O on Streams}, aswell as functions for performing low-level control operations for whichthere are no equivalents on streams.Stream-level I/O is more flexible and usually more convenient;therefore, programmers generally use the descriptor-level functions onlywhen necessary. These are some of the usual reasons:@itemize @bullet@itemFor reading binary files in large chunks.@itemFor reading an entire file into core before parsing it.@itemTo perform operations other than data transfer, which can only be donewith a descriptor. (You can use @code{fileno} to get the descriptorcorresponding to a stream.)@itemTo pass descriptors to a child process. (The child can create its ownstream to use a descriptor that it inherits, but cannot inherit a streamdirectly.)@end itemize@menu* Opening and Closing Files:: How to open and close file descriptors. * I/O Primitives:: Reading and writing data.* File Position Primitive:: Setting a descriptor's file position. * Descriptors and Streams:: Converting descriptor to stream or vice-versa.* Stream/Descriptor Precautions:: Precautions needed if you use both descriptors and streams.* Waiting for I/O:: How to check for input or output on multiple file descriptors.* Control Operations:: Various other operations on file descriptors.* Duplicating Descriptors:: Fcntl commands for duplicating file descriptors.* Descriptor Flags:: Fcntl commands for manipulating flags associated with file descriptors. * File Status Flags:: Fcntl commands for manipulating flags associated with open files.* File Locks:: Fcntl commands for implementing file locking.* Interrupt Input:: Getting an asynchronous signal when input arrives.@end menu@node Opening and Closing Files@section Opening and Closing Files@cindex opening a file descriptor@cindex closing a file descriptorThis section describes the primitives for opening and closing filesusing file descriptors. The @code{open} and @code{creat} functions aredeclared in the header file @file{fcntl.h}, while @code{close} isdeclared in @file{unistd.h}.@pindex unistd.h@pindex fcntl.h@comment fcntl.h@comment POSIX.1@deftypefun int open (const char *@var{filename}, int @var{flags}[, mode_t @var{mode}])The @code{open} function creates and returns a new file descriptorfor the file named by @var{filename}. Initially, the file positionindicator for the file is at the beginning of the file. The argument@var{mode} is used only when a file is created, but it doesn't hurtto supply the argument in any case.The @var{flags} argument controls how the file is to be opened. This isa bit mask; you create the value by the bitwise OR of the appropriateparameters (using the @samp{|} operator in C).@xref{File Status Flags}, for the parameters available.The normal return value from @code{open} is a non-negative integer filedescriptor. In the case of an error, a value of @code{-1} is returnedinstead. In addition to the usual file name syntax errors (@pxref{FileName Errors}), the following @code{errno} error conditions are definedfor this function:@table @code@item EACCESThe file exists but is not readable/writable as requested by the @var{flags}argument.@item EEXISTBoth @code{O_CREAT} and @code{O_EXCL} are set, and the named file alreadyexists.@item EINTRThe @code{open} operation was interrupted by a signal.@xref{Interrupted Primitives}.@item EISDIRThe @var{flags} argument specified write access, and the file is a directory.@item EMFILEThe process has too many files open.@item ENFILEThe entire system, or perhaps the file system which contains thedirectory, cannot support any additional open files at the moment.(This problem cannot happen on the GNU system.)@item ENOENTThe named file does not exist, and @code{O_CREAT} is not specified.@item ENOSPCThe directory or file system that would contain the new file cannot beextended, because there is no disk space left.@item ENXIO@code{O_NONBLOCK} and @code{O_WRONLY} are both set in the @var{flags}argument, the file named by @var{filename} is a FIFO (@pxref{Pipes andFIFOs}), and no process has the file open for reading.@item EROFSThe file resides on a read-only file system and any of @code{O_WRONLY},@code{O_RDWR}, and @code{O_TRUNC} are set in the @var{flags} argument,or @code{O_CREAT} is set and the file does not already exist.@end tableThe @code{open} function is the underlying primitive for the @code{fopen}and @code{freopen} functions, that create streams.@end deftypefun@comment fcntl.h@comment POSIX.1@deftypefn {Obsolete function} int creat (const char *@var{filename}, mode_t @var{mode})This function is obsolete. The call:@smallexamplecreat (@var{filename}, @var{mode})@end smallexample@noindentis equivalent to:@smallexampleopen (@var{filename}, O_WRONLY | O_CREAT | O_TRUNC, @var{mode})@end smallexample@end deftypefn@comment unistd.h@comment POSIX.1@deftypefun int close (int @var{filedes})The function @code{close} closes the file descriptor @var{filedes}.Closing a file has the following consequences:@itemize @bullet@item The file descriptor is deallocated.@itemAny record locks owned by the process on the file are unlocked.@itemWhen all file descriptors associated with a pipe or FIFO have been closed,any unread data is discarded.@end itemizeThe normal return value from @code{close} is @code{0}; a value of @code{-1}is returned in case of failure. The following @code{errno} errorconditions are defined for this function:@table @code@item EBADFThe @var{filedes} argument is not a valid file descriptor.@item EINTRThe @code{close} call was interrupted by a signal.@xref{Interrupted Primitives}.Here is an example of how to handle @code{EINTR} properly:@smallexampleTEMP_FAILURE_RETRY (close (desc));@end smallexample@end table@end deftypefunTo close a stream, call @code{fclose} (@pxref{Closing Streams}) insteadof trying to close its underlying file descriptor with @code{close}.This flushes any buffered output and updates the stream object toindicate that it is closed.@node I/O Primitives@section Input and Output PrimitivesThis section describes the functions for performing primitive input andoutput operations on file descriptors: @code{read}, @code{write}, and@code{lseek}. These functions are declared in the header file@file{unistd.h}.@pindex unistd.h@comment unistd.h@comment POSIX.1@deftp {Data Type} ssize_tThis data type is used to represent the sizes of blocks that can beread or written in a single operation. It is similar to @code{size_t},but must be a signed type.@end deftp@cindex reading from a file descriptor@comment unistd.h@comment POSIX.1@deftypefun ssize_t read (int @var{filedes}, void *@var{buffer}, size_t @var{size})The @code{read} function reads up to @var{size} bytes from the filewith descriptor @var{filedes}, storing the results in the @var{buffer}.(This is not necessarily a character string and there is no terminatingnull character added.)@cindex end-of-file, on a file descriptorThe return value is the number of bytes actually read. This might beless than @var{size}; for example, if there aren't that many bytes leftin the file or if there aren't that many bytes immediately available.The exact behavior depends on what kind of file it is. Note thatreading less than @var{size} bytes is not an error.A value of zero indicates end-of-file (except if the value of the@var{size} argument is also zero). This is not considered an error.If you keep calling @code{read} while at end-of-file, it will keepreturning zero and doing nothing else.If @code{read} returns at least one character, there is no way you cantell whether end-of-file was reached. But if you did reach the end, thenext read will return zero.In case of an error, @code{read} returns @code{-1}. The following@code{errno} error conditions are defined for this function:@table @code@item EAGAINNormally, when no input is immediately available, @code{read} waits forsome input. But if the @code{O_NONBLOCK} flag is set for the file(@pxref{File Status Flags}), @code{read} returns immediately withoutreading any data, and reports this error.@strong{Compatibility Note:} Most versions of BSD Unix use a differenterror code for this: @code{EWOULDBLOCK}. In the GNU library,@code{EWOULDBLOCK} is an alias for @code{EAGAIN}, so it doesn't matterwhich name you use.On some systems, reading a large amount of data from a character specialfile can also fail with @code{EAGAIN} if the kernel cannot find enoughphysical memory to lock down the user's pages. This is limited todevices that transfer with direct memory access into the user's memory,which means it does not include terminals, since they always useseparate buffers inside the kernel.Any condition that could result in @code{EAGAIN} can instead result in asuccessful @code{read} which returns fewer bytes than requested.Calling @code{read} again immediately would result in @code{EAGAIN}.@item EBADFThe @var{filedes} argument is not a valid file descriptor.@item EINTR@code{read} was interrupted by a signal while it was waiting for input.@xref{Interrupted Primitives}.@item EIOFor many devices, and for disk files, this error code indicatesa hardware error.@code{EIO} also occurs when a background process tries to read from thecontrolling terminal, and the normal action of stopping the process bysending it a @code{SIGTTIN} signal isn't working. This might happen ifsignal is being blocked or ignored, or because the process group isorphaned. @xref{Job Control}, for more information about job control,and @ref{Signal Handling}, for information about signals.@end tableThe @code{read} function is the underlying primitive for all of thefunctions that read from streams, such as @code{fgetc}.@end deftypefun@cindex writing to a file descriptor@comment unistd.h@comment POSIX.1@deftypefun ssize_t write (int @var{filedes}, const void *@var{buffer}, size_t @var{size})The @code{write} function writes up to @var{size} bytes from@var{buffer} to the file with descriptor @var{filedes}. The data in@var{buffer} is not necessarily a character string and a null character isoutput like any other character.The return value is the number of bytes actually written. This isnormally the same as @var{size}, but might be less (for example, if thephysical media being written to fills up).In the case of an error, @code{write} returns @code{-1}. The following@code{errno} error conditions are defined for this function:@table @code@item EAGAINNormally, @code{write} blocks until the write operation is complete.But if the @code{O_NONBLOCK} flag is set for the file (@pxref{ControlOperations}), it returns immediately without writing any data, andreports this error. An example of a situation that might cause theprocess to block on output is writing to a terminal device that supportsflow control, where output has been suspended by receipt of a STOPcharacter.@strong{Compatibility Note:} Most versions of BSD Unix use a differenterror code for this: @code{EWOULDBLOCK}. In the GNU library,@code{EWOULDBLOCK} is an alias for @code{EAGAIN}, so it doesn't matterwhich name you use.On some systems, writing a large amount of data from a character specialfile can also fail with @code{EAGAIN} if the kernel cannot find enoughphysical memory to lock down the user's pages. This is limited todevices that transfer with direct memory access into the user's memory,which means it does not include terminals, since they always useseparate buffers inside the kernel.@item EBADFThe @var{filedes} argument is not a valid file descriptor.@item EFBIGThe size of the file is larger than the implementation can support.@item EINTRThe @code{write} operation was interrupted by a signal while it wasblocked waiting for completion. @xref{Interrupted Primitives}.@item EIOFor many devices, and for disk files, this error code indicatesa hardware error.@item ENOSPCThe device is full.@item EPIPEThis error is returned when you try to write to a pipe or FIFO thatisn't open for reading by any process. When this happens, a @code{SIGPIPE}signal is also sent to the process; see @ref{Signal Handling}.@end tableUnless you have arranged to prevent @code{EINTR} failures, you shouldcheck @code{errno} after each failing call to @code{write}, and if theerror was @code{EINTR}, you should simply repeat the call.@xref{Interrupted Primitives}. The easy way to do this is with the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -