显示如下:
SENDFILE(2) Linux Programmer’s Manual SENDFILE(2)
NAME
sendfile - transfer data between file descriptors
SYNOPSIS
#include
ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);
DESCRIPTION
sendfile() copies data between one file descriptor and another.
Because this copying is done within the kernel, sendfile() is more
efficient than the combination of read(2) and write(2), which would
require transferring data to and from user space.
in_fd should be a file descriptor opened for reading and out_fd should
be a descriptor opened for writing.
If offset is not NULL, then it points to a variable holding the file
offset from which sendfile() will start reading data from in_fd. When
sendfile() returns, this variable will be set to the offset of the byte
following the last byte that was read. If offset is not NULL, then
sendfile() does not modify the current file offset of in_fd; otherwise
the current file offset is adjusted to reflect the number of bytes read
from in_fd.
count is the number of bytes to copy between the file descriptors.
Presently (Linux 2.6.9): in_fd, must correspond to a file which sup‐
ports mmap(2)-like operations (i.e., it cannot be a socket); and out_fd
must refer to a socket.
Applications may wish to fall back to read(2)/write(2) in the case
where sendfile() fails with EINVAL or ENOSYS.
RETURN VALUE
If the transfer was successful, the number of bytes written to out_fd
is returned. On error, -1 is returned, and errno is set appropriately.
这些日子编写网络相关的程序,偶尔发现这个api,据说效率奇高。sendfile()在在两个文件描述符之间完成数据拷贝操作,该操作是内核中完成的,所以称为"零拷贝"。sendfile函数比起read和write函数高效的原因在于read和write是要把数据拷贝到用户应用层操作而sendfile不需要。
参数说明:
out_fd 是已经打开了,用于写操作(write)的文件描述符;
in_fd 是已经打开了,用于读操作(read)的文件描述符;
offset 偏移量;表示sendfile函数从in_fd中的哪一偏移量开始读取数据.如果是零表示从文件的开始读,否则从相应的便宜量读取.如果是循环读取的时候,下一次offset值应为sendfile函数返回值加上本次的offset的值;
count是在两个描述符之间拷贝的字节数(bytes)。
目前手头时间比较紧迫,抽空出来写个测试程序看看使用这个api与使用其他api到底效率差别有多大。
返回值:
如果成功的拷贝,返回写操作到out_fd的字节数,错误返回-1,并相应的设置error信息.
EAGAIN 无阻塞I/O设置O_NONBLOCK时,写操作(write)阻塞了;
EBADF 输出或者输入的文件描述符没有打开;
EFAULT 错误的地址;
EINVAL 描述符不可用或者锁定了,或者用mmap()函数操作的in_fd不可用;
EIO 当读取(read)in_fd时发生未知错误;
ENOMEM 读(read)in_fd时内存不足。
目前手头时间比较紧迫,抽空出来写个测试程序看看使用这个api与使用其他api到底效率差别有多大。