On success, readv()andwritev()return the number of bytes read or written, respectively. This number should be the sum of allcount iov_lenvalues. On error, the system calls return-1, and seterrnoas appropriate. These system calls can experience any of the errors of theread()andwrite()system calls, and will, upon receiving such errors, set the sameerrnocodes. In addition, the standards define two other error situations.
First, because the return type is anssize_t, if the sum of allcount iov_lenvalues is greater thanSSIZE_MAX, no data will be transferred,-1will be returned, anderrnowill be set toEINVAL.
Second, POSIX dictates thatcountmust be larger than zero, and less than or equal toIOV_MAX, which is defined in<limits.h>. In Linux,IOV_MAXis currently1024. Ifcountis0, the system calls return0.* Ifcountis greater thanIOV_MAX, no data is transferred, the calls return-1, anderrnois set toEINVAL.
Optimizing the Count
During a vectored I/O operation, the Linux kernel must allocate internal data structures to represent each segment. Normally, this allocation would occur dynamically, based on the size of count. As an optimization, however, the Linux kernel creates a small array of segments on the stack that it uses ifcountis sufficiently small, negating the need to dynamically allocate the segments, and thereby providing a small boost in performance. This threshold is currently eight, so ifcountis less than or equal to8, the vectored I/O operation occurs in a very memory-efficient manner off of the processí kernel stack.
Most likely, you wonít have a choice about how many segments you need to transfer at once in a given vectored I/O operation. If you are flexible, however, and are debating over a small value, choosing a value of eight or less definitely improves efficiency.
writev( ) example
Letís consider a simple example that writes out a vector of three segments, each containing a string of a different size. This self-contained program is complete enough to demonstrate writev(), yet simple enough to serve as a useful code snippet: