1#include <unistd.h>2#include <sys/types.h>34static ssize_t5sendfile(int out, int in, off_t *offset, size_t count)6{7 off_t start;8 char buf[4096];9 ssize_t rw, rr;10 size_t c, max, written;1112 /* XXX: Technically, sendfile should not modify the file offset if13 * offset is not NULL, this implementation ignore this requirement. */1415 if (offset) {16 start = *offset;17 if (lseek(in, start, SEEK_SET) == -1)18 return -1;19 }2021 written = 0;22 for (c = count; c > 0; c -= rw) {23 if ((max = sizeof(buf)) > c)24 max = c;2526 rr = read(in, buf, max);27 if (rr == 0)28 break;29 else if (rr == -1)30 return -1;3132 if ((rw = write(out, buf, rr)) == -1)33 return -1;34 written += rw;3536 /* If a short write occured, seek back and return */37 if (rw < rr) {38 if (lseek(in, rw - rr, SEEK_CUR) == -1)39 return -1;40 break;41 }42 }4344 if (offset)45 *offset = start + written;46 return written;47}