1
0
mirror of https://github.com/fumiama/simple-http-server.git synced 2026-06-21 12:20:23 +08:00

cat改用sendfile

This commit is contained in:
源文雨
2021-06-07 15:51:13 +08:00
parent 0b26036fae
commit a181a3b263

View File

@@ -20,6 +20,10 @@
#include <stdlib.h> #include <stdlib.h>
#include <pthread.h> #include <pthread.h>
#if !__APPLE__
#include <sys/sendfile.h>
#endif
#define ISspace(x) isspace((int)(x)) #define ISspace(x) isspace((int)(x))
#define SERVER_STRING "Server: tinyhttpd edited by fumiama/0.1.0\r\n" #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 * Parameters: the client socket descriptor
* FILE pointer for the file to cat */ * FILE pointer for the file to cat */
/**********************************************************************/ /**********************************************************************/
struct sf_hdtr hdtr;
void cat(int client, FILE *resource) { void cat(int client, FILE *resource) {
char buf[1024]; fseek(resource, 0, SEEK_END);
size_t size = 0; off_t len = 0;
#if __APPLE__
while ((size = fread(buf, sizeof(char), 1024, resource))) send(client, buf, size, 0); 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)); numchars = get_line(client, buf, sizeof(buf));
resource = fopen(filename, "rb"); resource = fopen(filename, "rb");
if (resource == NULL) if (resource == NULL) not_found(client);
not_found(client); else {
else
{
headers(client, filename); headers(client, filename);
cat(client, resource); cat(client, resource);
} }