linux高级IO之readv/writev

来源:互联网 发布:中海油投标软件下载 编辑:程序博客网 时间:2024/06/11 19:43

readv和writev可以同时操作多个缓冲区。

函数的使用很简单,

以readv为例:

#include <stdio.h>
#include <sys/uio.h>
#include <unistd.h>
#include <string.h>
int main()
{
    char str0[2] = {0x00};
    char str1[2] = {0x00};
    struct iovec buff[2] = {0x00};
    buff[0].iov_base = str0;
    buff[0].iov_len = sizeof(str0);
    buff[1].iov_base = str1;
    buff[1].iov_len = sizeof(str0);
    readv(STDIN_FILENO, buff, 2);
    fputs(str0, stdout);
    fputs(str1, stdout);
    return 0;
}

需要注意的是:readv和read均指定了读取的长度,若输入内容超过此长度,则会自动截断数据。此时需要循环读取。在本例中,为readv设置了两个缓冲区,知道前一个缓冲区读满,第二个缓冲区才开始读数据。比如输入abcd四个字符。则两个缓冲区分别保存ab,cd。若输入abcde,则e会被截断。

下面来看writev的用法,同样很简单。

#include <stdio.h>
#include <sys/uio.h>
#include <unistd.h>
#include <string.h>
int main()
{
    char *str0 = "str0";
    char *str1 = "str1";
    struct iovec buff[2] = {0x00};
    buff[0].iov_base = str0;
    buff[0].iov_len = strlen(str0);
    buff[1].iov_base = str1;
    buff[1].iov_len = strlen(str0);
    writev(STDOUT_FILENO, buff, 2);
    return 0;
}
0 0