使用散点图处理短读/写的技术? [英] Techniques for handling short reads/writes with scatter-gather?

查看:77
本文介绍了使用散点图处理短读/写的技术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分散收集-readv()/writev()/preadv()/pwritev()-在单个系统调用中读取/写入可变数量的iovec结构.基本上,它从第0个iovec到第N个按顺序读取/写入每个缓冲区.但是,根据文档,它在readv/writev调用上返回的次数也可能少于请求的返回数.我想知道是否有一种标准/最佳实践/优雅的方式来处理这种情况.

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 sequentially from the 0th iovec to the Nth. However according to the documentation it can also return less on the readv/writev calls than was requested. I was wondering if there is a standard/best practice/elegant way to handle that situation.

如果我们只处理一堆字符缓冲区或类似字符,那没什么大不了的.但是,好处之一是使用散点图聚集作为单独的iovec项的结构和/或离散变量.您如何处理readv/writev只读/写一部分结构或一半长度或类似内容的情况.

If we are just handling a bunch of character buffers or similar this isn't a big deal. But one of the niceties is using scatter-gather for structs and/or discrete variables as the individual iovec items. How do you handle the situation where the readv/writev only reads/writes a portion of a struct or half of a long or something like that.

以下是我所得到的一些人为设计的代码:

Below is some contrived code of what I am getting at:

int fd;

struct iovec iov[3];

long aLong = 74775767;
int  aInt  = 949;
char aBuff[100];  //filled from where ever

ssize_t bytesWritten = 0;
ssize_t bytesToWrite = 0;

iov[0].iov_base = &aLong;
iov[0].iov_len = sizeof(aLong);
bytesToWrite += iov[0].iov_len;

iov[1].iov_base = &aInt;
iov[1].iov_len = sizeof(aInt);
bytesToWrite += iov[1].iov_len;

iov[2].iov_base = &aBuff;
iov[2].iov_len = sizeof(aBuff);
bytesToWrite += iov[2].iov_len;

bytesWritten = writev(fd, iov, 3);

if (bytesWritten == -1)
{
    //handle error
}

if (bytesWritten < bytesToWrite)
    //how to gracefully continue?.........

推荐答案

使用如下所示的循环来推进部分处理的iov:

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;
}

请注意,如果不检查cur < count,您将读到iov的末尾,该末尾可能包含零.

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

这篇关于使用散点图处理短读/写的技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆