目录
最近使用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
}
}