How to deal if writev only write part of the data?

2019-09-16 08:17发布

问题:

My data is naturally segmented, and comes from different sources so I use writev function as follows.

char *buf0 = "short string\n";
struct bar *my_bar;
my_baz = get_my_baz();
iov[0].iov_base = buf0;
iov[0].iov_len = strlen(buf0);
iov[1].iov_base = my_bar;
iov[1].iov_len = sizeof (struct bar);
bytes_written = writev (sockfd, iov, 3);

I want to send all my data. What if writev only write partial data in one time, for example:

bytes_written = 1;

How do I to continue to send the remain data? In write function, we can do as follows enter link description here, how about writev?

回答1:

  1. Increment iov[0].iov_base by bytes_written.
  2. Decrement iov[0].iov_len by bytes_written.
  3. Take care of underflows, i.e. if iov[0].iov_len goes negative, remember it, set it to zero, and propagate the difference into iov[1] in the same way as (1) and (2), and so on until closure.

However if you're in blocking mode this is a non-issue, as the case of a short write can never arise.



标签: linux sockets