From a181a3b263af88346886373ae83f31be8f2dd04c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BA=90=E6=96=87=E9=9B=A8?= <41315874+fumiama@users.noreply.github.com> Date: Mon, 7 Jun 2021 15:51:13 +0800 Subject: [PATCH] =?UTF-8?q?cat=E6=94=B9=E7=94=A8sendfile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server.c | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/server.c b/server.c index 70ae616..6f17115 100644 --- a/server.c +++ b/server.c @@ -20,6 +20,10 @@ #include #include +#if !__APPLE__ + #include +#endif + #define ISspace(x) isspace((int)(x)) #define SERVER_STRING "Server: tinyhttpd edited by fumiama/0.1.0\r\n" @@ -150,11 +154,18 @@ void bad_request(int client) { * Parameters: the client socket descriptor * FILE pointer for the file to cat */ /**********************************************************************/ +struct sf_hdtr hdtr; void cat(int client, FILE *resource) { - char buf[1024]; - size_t size = 0; - - while ((size = fread(buf, sizeof(char), 1024, resource))) send(client, buf, size, 0); + fseek(resource, 0, SEEK_END); + off_t len = 0; + #if __APPLE__ + sendfile(fileno(resource), client, 0, &len, &hdtr, 0); + #else + off_t file_size = ftell(resource); + rewind(resource); + sendfile(client, fileno(resource), &len, file_size); + #endif + printf("Send %u bytes.\n", len); } /**********************************************************************/ @@ -412,10 +423,8 @@ void serve_file(int client, const char *filename) { numchars = get_line(client, buf, sizeof(buf)); resource = fopen(filename, "rb"); - if (resource == NULL) - not_found(client); - else - { + if (resource == NULL) not_found(client); + else { headers(client, filename); cat(client, resource); }