Develop a multi-threaded C file server using sendfile() for zero-copy transfer directly from disk cache to network socket. Benchmark the CPU usage difference against a standard read/write loop.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Proposing multi-threaded C server with sendfile and benchmarking
I'm preparing a detailed C server example that uses threads to handle clients and toggles between sendfile and read/write file sending based on an environment variable. The answer will include complete code, compilation instructions, guidance on benchmarking CPU usage differences with tools like ApacheBench and top or perf, and notes on expected zero-copy CPU savings.
On Linux you can take advantage of the sendfile(2) API to have the kernel pull pages out of the page cache and push them straight into a TCP socket without ever copying them into user space. To see what that buys you in CPU consumption, you need two implementations of the same server logic: one that shovels bytes with a read(2)/write(2) loop and one that uses sendfile(2).
The following is a minimal threaded file server in C. It listens on a TCP port, spawns a detached thread per connection, reads a single line containing the path of a file to send (relative to a base directory), and then sends it using either a user‑space loop or sendfile. To keep the benchmark focused, no HTTP headers or logging is generated:
c
// fileserver.c
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define PORT 8080
#define BACKLOG 128
#define BUFSIZE 16384
#define BASEDIR "./data"
#define USE_SENDFILE 1 /* set to 0 for read/write variant */
static void *client_thread(void *arg) {
int client_fd = (intptr_t)arg;
char pathbuf[1024];
ssize_t n = 0, total = 0;
/* very simple line-oriented protocol: one line with path */
while (total < sizeof(pathbuf) - 1) {
n = read(client_fd, pathbuf + total, sizeof(pathbuf) - 1 - total);
if (n <= 0) {
close(client_fd);
return NULL;
}
total += n;
if (memchr(pathbuf, '\n', total)) break;
}
pathbuf[total] = '\0';
char *newline = strchr(pathbuf, '\n');
if (newline) *newline = '\0';
/* construct full path under BASEDIR to avoid escaping */
char fullpath[2048];
snprintf(fullpath, sizeof(fullpath), "%s/%s", BASEDIR, pathbuf);
int fd = open(fullpath, O_RDONLY);
if (fd < 0) {
perror("open");
close(client_fd);
return NULL;
}
struct stat st;
if (fstat(fd, &st) != 0) {
perror("fstat");
close(fd);
close(client_fd);
return NULL;
}
#if USE_SENDFILE
off_t offset = 0;
off_t to_send = st.st_size;
while (to_send > 0) {
ssize_t sent = sendfile(client_fd, fd, &offset, to_send);
if (sent <= 0) {
if (errno == EINTR) continue;
perror("sendfile");
break;
}
to_send -= sent;
}
#else
char buf[BUFSIZE];
while (1) {
ssize_t r = read(fd, buf, sizeof(buf));
if (r < 0) {
if (errno == EINTR) continue;
perror("read");
break;
} else if (r == 0) {
break; /* EOF */
}
ssize_t written = 0;
while (written < r) {
ssize_t w = write(client_fd, buf + written, r - written);
if (w < 0) {
if (errno == EINTR) continue;
perror("write");
goto out;
}
written += w;
}
}
#endif
out:
close(fd);
close(client_fd);
return NULL;
}
int main(void) {
signal(SIGPIPE, SIG_IGN); /* don't die on client abort */
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) { perror("socket"); exit(EXIT_FAILURE); }
int optval = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_ANY),
.sin_port = htons(PORT)
};
if (bind(listen_fd, (struct sockaddr *)&addr, sizeof addr) != 0) {
perror("bind"); exit(EXIT_FAILURE);
}
if (listen(listen_fd, BACKLOG) != 0) {
perror("listen"); exit(EXIT_FAILURE);
}
printf("Listening on port %d\n", PORT);
for (;;) {
struct sockaddr_in cliaddr;
socklen_t clilen = sizeof cliaddr;
int client_fd = accept(listen_fd, (struct sockaddr *)&cliaddr, &clilen);
if (client_fd < 0) {
if (errno == EINTR) continue;
perror("accept");
continue;
}
pthread_t tid;
pthread_create(&tid, NULL, client_thread, (void *)(intptr_t)client_fd);
pthread_detach(tid);
}
close(listen_fd);
return 0;
}
For benchmarking you want multiple concurrent requests to put load on the system. You can use ab or wrk to generate load; because the protocol is not HTTP you can write a small loop in shell to fire many connections:
sh
# fire 50 concurrent netcat requests in the background
for i in $(seq 1 50); do
{ echo "testfile"; } | nc 127.0.0.1 8080 > /dev/null &
done
wait
While this runs, observe CPU usage of the server process with top, pidstat, or perf:
sh
pidstat -u -p $(pidof fileserver_sendfile) 1
or run the load under perf stat:
sh
perf stat -p $(pidof fileserver_sendfile) -e task-clock,cycles,instructions,cache-misses sleep 10
Do the same with fileserver_rw.
On a reasonably fast machine you should see that the sendfile variant consumes significantly fewer user‑space cycles per byte transferred. For example, on a 100 MB file served to a local client with 10 concurrent connections, you might see something like:
code
sendfile: ~5–10% CPU in server process
read/write: ~25–35% CPU in server process
The exact numbers depend on hardware, kernel, and network stack, but the relative difference will show the benefit of zero‑copy.
If you prefer HTTP benchmarking tools, you can wrap this logic in a minimal HTTP responder (read first line of HTTP request, ignore headers, send 200 OK and body). The main change is to send proper headers before the file data. Tools like ab -n 1000 -c 50 http://127.0.0.1:8080/testfile will then exercise the server.
The important parts of the implementation are:
Thread‑per‑connection to handle multiple clients.
A compile‑time switch to choose between sendfile(2) and manual read/write.
Proper handling of partial sends and EINTR.
By running the same workload against both binaries and measuring CPU usage, you can quantify the difference between zero‑copy and user‑space buffered I/O on your system.