sendfile -- transfer data between two file descriptors


#include <sys/sendfile.h>

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


The sendfile() function shall copy data between the file descriptor in_fd, which must not be a socket, and the file descriptor out_fd, which must be a socket. in_fd should be opened for reading, and out_fd should be opened for writing.

The offset parameter points to a variable set to the file offset at which sendfile() shall start reading from in_fd, unless it is NULL. On exit, this variable shall contain the offset of the byte immediately after the last byte read. sendfile() shall not change the current file offset of in_fd, unless it is NULL. In that case, sendfile() shall adjust the current file offset to show how many bytes were read.

The count parameter specifies how many bytes to copy.

Return Value

On success, sendfile() shall return the number of bytes written to out_fd.

On failure, sendfile() shall return -1 and set errno appropriately, as follows.



Non-blocking I/O with O_NONBLOCK has been chosen, but the write would block.


The input file is not open for reading, or the output file is not open for writing.


Bad address.


An mmap()-like operation is unavailable for in_fd, or file descriptor is locked or invalid.


There was an unspecified error while reading.


There is not enough memory to read from in_fd.


sendfile() is usually faster than combining read() and write() calls, because it is part of the kernel. However, if it fails with EINVAL, falling back to read() and write() may be advisable.

It is advisable for performance reasons to use the TCP_CORK option of the tcp() function when sending header data with file contents to a TCP socket. This minimizes the number of packets.

See Also

mmap(), open(), socket(), splice().