The main convenience offered by readv , writev :
- It allows you to work with non-contiguous data blocks. that is, buffers should not be part of an array, but separately allocated.
- I / O is atomic. those. if you
writev , all the elements in the vector will be written in one continuous operation, and the recording of other processes will not occur between them.
eg. let's say your data is naturally segmented and comes from different sources:
struct foo *my_foo; struct bar *my_bar; struct baz *my_baz; my_foo = get_my_foo(); my_bar = get_my_bar(); my_baz = get_my_baz();
Now all three "buffers" are not one large contiguous block. But you want to write them adjacent to the file for any reason (say, for example, these are the fields in the file header for the file format).
If you use write , you need to choose between:
- Copy them into one block of memory using, say,
memcpy (overhead), and then a single call to write . Then the record will be atomic. - Making three separate
write calls (overhead). In addition, write calls from other processes may intersect between these write (not atomic).
If you use writev instead, all of this is good:
- You make exactly one system call, not
memcpy , to make one buffer out of three. - In addition, three buffers are written atomically, as one block writes. those. if other processes also write, then these records will not go between the recording of three vectors.
So you would do something like:
struct iovec iov[3]; iov[0].iov_base = my_foo; iov[0].iov_len = sizeof (struct foo); iov[1].iov_base = my_bar; iov[1].iov_len = sizeof (struct bar); iov[2].iov_base = my_baz; iov[2].iov_len = sizeof (struct baz); bytes_written = writev (fd, iov, 3);
Sources:
ArjunShankar May 09 '12 at 17:07 2012-05-09 17:07
source share