天天看点

Fast Scatter-Gather I/O

Instead, many platforms provide special high-speed primitives to perform these scatter-gather operations in a single kernel call. The GNU C library will provide an emulation on any system that lacks these primitives, so they are not a portability threat. They are defined in <code>sys/uio.h</code>.

These functions are controlled with arrays of <code>iovec</code> structures, which describe the location and size of each buffer.

The <code>iovec</code> structure describes a buffer. It contains two fields: <dl></dl> <dt></dt> <code>void *iov_base</code> <dd>Contains the address of a buffer.</dd> <code>size_t iov_len</code> <dd>Contains the length of the buffer. </dd>
The <code>readv</code> function reads data from filedes and scatters it into the buffers described in vector, which is taken to be count structures long. As each buffer is filled, data is sent to the next. Note that <code>readv</code> is not guaranteed to fill all the buffers. It may stop at any point, for the same reasons <code>read</code> would. The return value is a count of bytes (not buffers) read, 0 indicating end-of-file, or -1 indicating an error. The possible errors are the same as in <code>read</code>.
The <code>writev</code> function gathers data from the buffers described in vector, which is taken to be count structures long, and writes them to <code>filedes</code>. As each buffer is written, it moves on to the next. Like <code>readv</code>, <code>writev</code> may stop midstream under the same conditions <code>write</code> would. The return value is a count of bytes written, or -1 indicating an error. The possible errors are the same as in <code>write</code>.

Note that if the buffers are small (under about 1kB), high-level streams may be easier to use than these functions. However, <code>readv</code> and <code>writev</code> are more efficient when the individual buffers themselves (as opposed to the total output), are large. In that case, a high-level stream would not be able to cache the data effectively.

继续阅读