Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 14.6 readvandwritevFunctions 521


14.6 readvandwritev Functions


The readv and writev functions let us read into and write from multiple
noncontiguous buffers in a single function call. These operations arecalledscatter read
andgather write.
#include <sys/uio.h>
ssize_t readv(intfd,const struct iovec *iov,intiovcnt);
ssize_t writev(intfd,const struct iovec *iov,intiovcnt);
Both return: number of bytes read or written,−1 on error

The second argument to both functions is a pointer to an array ofiovecstructures:

struct iovec {
void *iov_base; /* starting address of buffer */
size_t iov_len; /* size of buffer */
};

The number of elements in theiovarray is specified byiovcnt.It is limited toIOV_MAX
(recall Figure2.11). Figure14.22 shows a diagram relating the arguments to these two
functions and theiovecstructure.

len0

len1

...

lenN

buffer0

buffer1

bufferN

iov[0].iov_base
iov[0].iov_len
iov[1].iov_base
iov[1].iov_len

iov[iovcnt− 1 ].iov_base
iov[iovcnt− 1 ].iov_len

len0

len1

lenN

Figure 14.22Theiovecstructureforreadvandwritev

Thewritevfunction gathers the output data from the buffers in order:iov[0],iov[1],
throughiov[iovcnt−1];writevreturns the total number of bytes output, which should
normally equal the sum of all the buffer lengths.
Thereadvfunction scatters the data into the buffers in order,always filling one
buffer beforeproceeding to the next.readvreturns the total number of bytes that were
read. A count of 0 is returned if there is no moredata and the end of file is encountered.

These two functions originated in 4.2BSD and werelater added to SVR4. These two functions
areincluded in the XSI option of the Single UNIX Specification.
Free download pdf