A very common operation of Web servers these days is transferring files to clients. They do that by reading the files’ contents from a disk and writing it back to the clients’ sockets.
The copying of the file on Linux/UNIX, for example, could be done in a loop using read/write system calls:
import os ... while True: data = os.read(filefd, 4096) if not data: break os.write(socketfd, data)
On the surface this looks perfectly fine, but for transferring large files, when pre-processing of the file contents isn’t necessary, this is pretty inefficient.
That’s where the sendfile system call comes in handy. It provides a nice optimization for this particular use case by doing all the copying from the file descriptor to the socket descriptor completely in the kernel space: