manによると,fd間でデータのコピーを行うけど,read()とwrite()が不要なので効率が良いとのこと.
実際にやるとこんな感じになります..
[masami@moonlight:~]% touch a.txt b.txt [masami@moonlight:~]% echo "foobar" > a.txt [masami@moonlight:~]% emacs sendfile.c [masami@moonlight:~]% gcc sendfile.c [masami@moonlight:~]% ./a.out 7 bytes were written to b.txt [masami@moonlight:~]% cat b.txt foobar [masami@moonlight:~]%
ソースはこれです.
#include <stdio.h> #include <sys/sendfile.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> int main(int argc, char **argv) { int in_fd, out_fd; struct stat st; int count; in_fd = open("./a.txt", O_RDONLY); assert(in_fd != -1); out_fd = open("./b.txt", O_RDWR); assert(out_fd != -1); stat("./a.txt", &st); count = sendfile(out_fd, in_fd, NULL, st.st_size); printf("%d bytes were written to b.txt\n", count); return 0; }
データ転送するには便利ですかね.