Techniques for handling short reads/writes with scatter-gather?

后端 未结 3 1334
独厮守ぢ
独厮守ぢ 2021-02-06 01:28

Scatter-gather - readv()/writev()/preadv()/pwritev() - reads/writes a variable number of iovec structs in a single system call. Basically it reads/write each buffer sequentiall

3条回答
  •  孤街浪徒
    2021-02-06 02:02

    Use a loop like the following to advance the partially-processed iov:

    for (;;) {
        written = writev(fd, iov+cur, count-cur);
        if (written < 0) goto error;
        while (cur < count && written >= iov[cur].iov_len)
            written -= iov[cur++].iov_len;
        if (cur == count) break;
        iov[cur].iov_base = (char *)iov[cur].iov_base + written;
        iov[cur].iov_len -= written;
    }
    

    Note that if you don't check for cur < count you will read past the end of iov which might contain zero.

提交回复
热议问题