linux sendfile 使用,以及一些坑

目录

函数原型 && 使用手册说明

最近使用sendfile 遇到了大文件传输超过2G的文件只能传输2G

代码示例


函数原型 && 使用手册说明

ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);

 

in_fd 应该是为读取而打开的文件描述符,而 out_fd 应该是为写入而打开的描述符。

如果 offset 不为 NULL,则它指向一个保存文件偏移量的变量,sendfile() 将从该变量开始从 in_fd 读取数据。 当 sendfile() 返回时,这个变量将被设置为跟随字节的偏移量读取的最后一个字节。 如果 offset 不为 NULL,则 sendfile() 不会修改in_fd; 否则调整文件偏移量以反映从 in_fd 读取的字节数。

如果 offset 为 NULL,则从 in_fd 开始读取文件偏移量的数据,offset会被更新。

count 是要在文件描述符之间复制的字节数。

in_fd 参数必须对应于支持类似 mmap(2) 操作的文件(即,它不能是socket)。

最近使用sendfile 遇到了大文件传输超过2G的文件只能传输2G

这句话里面给出了答案

         If the transfer was successful, the number of bytes written to out_fd is returned.  Note  that  a  successful  call  to  sendfile()  may  write fewer bytes than requested; the caller should be prepared to retry the call if there were unsent bytes. 

        如果传输成功,则返回写入 out_fd 的字节数。 请注意,对 sendfile() 的成功调用可能写入的字节数少于请求的字节数; 如果有未发送的字节,调用者应该准备好重新调用。

代码示例

#include <sys/sendfile.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

void TestSendFile(int out_fd, int in_fd)
{
    struct stat stat = {};
    int ret = fstat(in_fd, &stat);
    if (ret == -1 || stat.st_size < 0)
    {
        // print error message
    }
    long offset = 0;
    while ((ret = sendfile(out_fd, in_fd, &offset, stat.st_size)) > 0);
    if (ret == -1)
    {
        // print error message
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值