Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 14.5 Asynchronous I/O 511



  1. Enable asynchronous I/O on the descriptor by callingfcntlwith a command
    ofF_SETFLto set theO_ASYNCfile status flag (Figure3.10).


Step 3 can be performed only on descriptors that refer to terminals or networks, which
is a fundamental limitation of the BSD asynchronous I/O facility.
For theSIGURGsignal, we need perform only steps 1 and 2. SIGURGis generated
only for descriptors that refer to network connections that support out-of-band data,
such as TCP connections.

14.5.3 POSIX Asynchronous I/O


The POSIX asynchronous I/O interfaces give us a consistent way to perform
asynchronous I/O, regardless of the type of file. These interfaces wereadopted from
the real-time draft standard, which themselves were an option in the Single UNIX
Specification. InVersion 4, the Single UNIX Specification moved these interfaces to the
base, so they arenow required to be supported by all platforms.
The asynchronous I/O interfaces use AIO control blocks to describe I/O operations.
Theaiocbstructuredefines an AIO control block. It contains at least the fields shown
in the following structure(implementations might include additional fields):

struct aiocb {
int aio_fildes; /* file descriptor */
off_t aio_offset; /* file offset for I/O */
volatile void *aio_buf; /* buffer for I/O */
size_t aio_nbytes; /* number of bytes to transfer */
int aio_reqprio; /* priority */
struct sigevent aio_sigevent; /* signal information */
int aio_lio_opcode; /* operation for list I/O */
};

Theaio_fildesfield is the file descriptor open for the file to be read or written.
The read or write starts at the offset specified byaio_offset.For a read, data is
copied to the buffer that begins at the address specified byaio_buf.For a write, data
is copied from this buffer.Theaio_nbytesfield contains the number of bytes to read
or write.
Note that we have to provide an explicit offset when we perform asynchronous
I/O. The asynchronous I/O interfaces don’t affect the file offset maintained by the
operating system. This won’t be a problem as long as we never mix asynchronous I/O
functions with conventional I/O functions on the same file in a process. Also note that
if we write to a file opened in append mode (withO_APPEND)using an asynchronous
interface, theaio_offsetfield in the AIO control block is ignored by the system.
The other fields don’t correspond to the conventional I/O functions. The
aio_reqpriofield is a hint that gives applications a way to suggest an ordering for the
asynchronous I/O requests. The system has only limited control over the exact
ordering, however, so there is no guarantee that the hint will be honored. The
aio_lio_opcodefield is used only with list-based asynchronous I/O, which we’ll
Free download pdf