Designing a multi-threaded file server
I’m considering using epoll in level-triggered mode for simplicity. I'll define a simple text protocol where the client sends "GET filename\n" and the server responds with the file content or "ERROR\n". For handling concurrency, I think about using pread in worker threads, which might eliminate the need for asynchronous I/O, since disk calls are blocking. I’m outlining two threading models: one with a main boss thread for network I/O and worker threads for file reading. The other has each worker thread managing its own epoll.Structuring connection handling
I’m considering using a struct connection that includes fields like file descriptor, read buffer, and write buffer, possibly with an offset and atomic reference counts. To keep it simple, I'll handle small files by reading the entire file into memory first. I think a thread-safe queue can manage tasks efficiently, where each worker pops a task, opens the file, reads it, and sets the connection's state to SENDING_RESPONSE.
Since epoll runs in the main thread, I’ll need to ensure thread-safe updates, possibly using eventfd for notifications. Alternatively, I could mark connections as ready and use epoll_ctl from the worker thread, but I must guard connection data with a mutex. Ultimately, it's essential to maintain epoll for I/O multiplexing.Creating a minimal educational server
I want to create a minimal educational server, so I’ll skip advanced parts. I’ll mention that a proper production server would need more error handling.
For the implementation, I’ll need a thread pool that creates N worker threads, each looping to pop tasks from a mutex-protected queue. Each task will be a pointer to a connection and the requested filename.
I'll manage connections with a global map from file descriptor to connection pointer, intentionally simplifying allocation from an array. Using epoll_event.data.ptr to store a pointer to the connection struct will streamline this process. When a new connection is accepted, I’ll allocate and set the properties like file descriptor and state, adding it to epoll. When input events occur, I’ll read into the buffer, parse the request, and create a task for the worker.Planning server functionality
I need to ensure we don’t read more data than necessary, so I’ll disable EPOLLIN for a connection while the worker is processing it. After the worker finishes, it will update the connection's write buffer and state to SENDING, and I’ll modify the epoll interest to EPOLLOUT for sending.
I should also consider handling partial sends, EAGAIN errors, and tracking sent bytes. We’ll close the socket after sending, simplifying the approach by not allowing multiple requests on the same connection. Each socket needs to be set to non-blocking.
I’m thinking of including a header for includes and #defines, compiling with -pthread, while keeping commentary concise. My plan includes an overview bullet list of features and protocol, one big C file around 250-350 LOC, plus build/run instructions.Designing the server code
I’m focusing on creating a minimal server design that includes the epoll loop, thread pool, and connection states. I’ll keep explanations brief.
To start, I'll set up basic includes and define constants like MAX_EVENTS, LISTEN_PORT, and others. I’ll define connection states as an enum and create a connection_t structure that holds important data, including buffers and locks.
Then, I’ll create a work item structure for the queue and define the global queue and epoll file descriptor for managing connections. The main function will create the listening socket, initialize epoll, and enter the event loop where I’ll handle connections based on events.
Within the event loop, when I accept connections, I’ll ensure they’re set to non-blocking. I’ll implement a reading handler that reads lines into the buffer, parses request data, and manages work items while changing connection states appropriately.
To manage sending responses, I’ll set connections to notify for writing once the response is ready. I’ll need to ensure thread safety when modifying epoll states from worker threads. Overall, the aim is a straightforward yet effective implementation for demonstration purposes.Managing connections safely
In this server demonstration, I need to close connections properly after a response. I’ll use epoll_ctl to remove the connection and close the file descriptor, ensuring no workers are using it.
To address potential concurrency issues, I’ll design the system so that a worker only processes one connection at a time. However, if a client disconnects during processing, it could lead to complexities.
For simplification, I’ll state that this basic server may ignore some error-handling and concurrency bugs. Instead of closing connections immediately on events like EPOLLHUP/EPOLLERR, I could set a "want_close" flag, checking it later.
I might also consider using a reference counting system or single-threaded architecture for simplicity, where each worker handles its own epoll and I/O tasks. This could mitigate concurrency challenges, allowing for clearer separation of responsibilities.Designing a multi-threaded server
I'm considering a multi-threaded server architecture that utilizes epoll for handling network I/O effectively. The main thread will listen for incoming connections and pass them to worker threads, which use blocking I/O for reading and sending data.
Each worker thread will maintain its own epoll instance and use a pipe for communication with the main thread. This way, I can avoid cross-thread concurrency issues by keeping each connection isolated within its worker.
Using a round-robin method allows the main thread to distribute tasks efficiently, ensuring better CPU and disk utilization. This design seems clean and simple while satisfying the requirements!Implementing file handling in a multi-threaded server
I'm thinking about how to handle file I/O when receiving a "GET" request. While one thread reads the file, we still have other worker threads ready for events, which should keep things responsive. I need to use epoll for network I/O and non-blocking sends.
I'll structure a connection to handle reads with a buffer and parse the request to extract the file path. Any errors will be handled gracefully. The server will respond with a simple protocol indicating success or failure, keeping the implementation straightforward and clear, while maintaining efficient state management across threads!Organizing worker thread management
I'm considering how to distribute work efficiently among worker threads. The main thread selects a worker in a round-robin fashion as new connections arrive, and I need to ensure that each worker can handle the connections without blocking. I'll set up pipes for communication and make sure they are non-blocking.
It's essential to manage error handling appropriately while minimizing complexity. I plan to implement the core functions for reading requests, processing them, and sending responses. My goal is clarity and efficiency while ensuring robust connections are maintained!Handling epoll events gracefully
I'm focusing on edge events in the epoll event loop. My approach involves treating EPOLLHUP, EPOLLRDHUP, and even EPOLLERR as disconnects by calling close_conn. The main challenge is ensuring I don't double-call functions like handle_read and close_conn since they may create conflicts if a connection has already been freed.
I’ll set up an efficient structure for handling events based on connection state while implementing sound memory management practices. Lastly, I want to allow for flexible port and document root configurations while maintaining clarity in the code.Designing the worker structure and workflow
I'm starting by designing the worker struct for the multi-threaded file server. Each worker will have fields like an ID, epfd, and notify FDs, using an allocated array for managing workers. I plan to set up the worker thread functions and handle connections through pipes.
Then, I'll focus on a simple accept loop in the main thread, keeping it blocking, while only using epoll for worker threads. I'll also include error handling and ensure proper signal management while considering concurrent execution. I'll keep the implementation simple yet efficient by defining necessary prototypes and structuring the code well. Below is a compact but complete example of a multi-threaded file server in C that uses epoll for I/O multiplexing.
Architecture:
-
One “acceptor” thread (main thread) that:
- Creates a listening socket.
- Accepts new client connections.
- Distributes them round-robin to worker threads.
-
N worker threads. Each worker:
- Has its own
epoll instance.
- Uses a pipe from the acceptor to receive new client FDs.
- Uses
epoll to manage:
- Its notification pipe.
- All client sockets it owns.
- For each client:
- Reads a simple request:
GET <relative_path>\n
- Reads the requested file into memory.
- Sends back:
OK <filesize>\n<file bytes> or
ERR <message>\n
- Closes the connection.
-
Network I/O is fully non-blocking and driven by epoll in the worker threads.
-
File I/O is blocking, but done in worker threads so it doesn’t stall other workers.
Protocol
Very simple line-based protocol (not HTTP):
Files are served relative to a “document root” directory (default: current directory).
Complete single-file server (Linux)
Save as epoll_file_server.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 <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define DEFAULT_PORT 9000
#define MAX_WORKERS 4
#define MAX_EVENTS 64
#define READ_BUFFER_SIZE 4096
#define MAX_PATH_LEN 4096
static const char *g_docroot = "."; /* document root directory */
/* Forward declarations */
struct worker;
typedef enum {
STATE_READING = 0,
STATE_WRITING = 1
} conn_state_t;
typedef struct connection {
int fd;
struct worker *worker; /* owner worker */
conn_state_t state;
char rbuf[READ_BUFFER_SIZE];
size_t rlen;
char *wbuf; /* response buffer */
size_t wlen;
size_t wpos;
} connection_t;
typedef struct worker {
int id;
int epfd;
int notify_receive_fd; /* read end of pipe from main/acceptor */
int notify_send_fd; /* write end of pipe (unused in worker) */
pthread_t thread;
} worker_t;
static worker_t g_workers[MAX_WORKERS];
static int g_num_workers = MAX_WORKERS;
/* Utility: set FD to non-blocking */
static int make_nonblocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl(F_GETFL)");
return -1;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
perror("fcntl(F_SETFL)");
return -1;
}
return 0;
}
static void close_connection(connection_t *c);
/* Modify epoll events for a connection */
static int conn_mod_events(connection_t *c, uint32_t events) {
struct epoll_event ev;
ev.events = events;
ev.data.ptr = c;
if (epoll_ctl(c->worker->epfd, EPOLL_CTL_MOD, c->fd, &ev) == -1) {
perror("epoll_ctl(MOD)");
return -1;
}
return 0;
}
/* Send an error message and switch to write state */
static void send_error(connection_t *c, const char *msg) {
const char *prefix = "ERR ";
size_t len_prefix = strlen(prefix);
size_t len_msg = strlen(msg);
size_t total = len_prefix + len_msg + 1; /* + '\n' */
char *buf = malloc(total);
if (!buf) {
fprintf(stderr, "malloc failed in send_error\n");
close_connection(c);
return;
}
size_t pos = 0;
memcpy(buf + pos, prefix, len_prefix);
pos += len_prefix;
memcpy(buf + pos, msg, len_msg);
pos += len_msg;
buf[pos++] = '\n';
c->wbuf = buf;
c->wlen = pos;
c->wpos = 0;
c->state = STATE_WRITING;
conn_mod_events(c, EPOLLOUT | EPOLLRDHUP | EPOLLHUP | EPOLLERR);
}
/* Read entire file into memory and build response */
static void handle_get_file(connection_t *c, const char *relpath) {
/* Basic validation: no absolute paths, no ".." */
if (relpath[0] == '/' || strstr(relpath, "..") != NULL) {
send_error(c, "invalid path");
return;
}
char fullpath[MAX_PATH_LEN];
if (snprintf(fullpath, sizeof(fullpath), "%s/%s", g_docroot, relpath) >= (int)sizeof(fullpath)) {
send_error(c, "path too long");
return;
}
int fd = open(fullpath, O_RDONLY);
if (fd == -1) {
perror("open");
send_error(c, "file not found");
return;
}
struct stat st;
if (fstat(fd, &st) == -1) {
perror("fstat");
close(fd);
send_error(c, "stat failed");
return;
}
if (!S_ISREG(st.st_mode)) {
close(fd);
send_error(c, "not a regular file");
return;
}
off_t fsize = st.st_size;
char header[64];
int hlen = snprintf(header, sizeof(header), "OK %lld\n", (long long)fsize);
if (hlen <= 0 || hlen >= (int)sizeof(header)) {
close(fd);
send_error(c, "internal error");
return;
}
size_t total = (size_t)hlen + (size_t)fsize;
char *buf = malloc(total);
if (!buf) {
fprintf(stderr, "malloc failed for file buffer\n");
close(fd);
send_error(c, "out of memory");
return;
}
memcpy(buf, header, (size_t)hlen);
ssize_t n;
size_t off = (size_t)hlen;
while (off < total) {
n = read(fd, buf + off, total - off);
if (n == -1) {
if (errno == EINTR)
continue;
perror("read(file)");
free(buf);
close(fd);
send_error(c, "read error");
return;
} else if (n == 0) {
break; /* EOF */
} else {
off += (size_t)n;
}
}
close(fd);
c->wbuf = buf;
c->wlen = off; /* actual bytes filled (should equal total) */
c->wpos = 0;
c->state = STATE_WRITING;
conn_mod_events(c, EPOLLOUT | EPOLLRDHUP | EPOLLHUP | EPOLLERR);
}
/* Parse a single-line "GET <path>" request and dispatch */
static void process_request(connection_t *c) {
/* Ensure null-termination of the first line */
char *newline = memchr(c->rbuf, '\n', c->rlen);
if (!newline) {
send_error(c, "no newline in request");
return;
}
*newline = '\0';
if (newline > c->rbuf && newline[-1] == '\r')
newline[-1] = '\0';
if (strncmp(c->rbuf, "GET ", 4) != 0) {
send_error(c, "expected GET");
return;
}
const char *path = c->rbuf + 4;
if (*path == '\0') {
send_error(c, "empty path");
return;
}
handle_get_file(c, path);
}
/* Close and free a connection */
static void close_connection(connection_t *c) {
if (!c) return;
epoll_ctl(c->worker->epfd, EPOLL_CTL_DEL, c->fd, NULL);
close(c->fd);
free(c->wbuf);
free(c);
}
/* Handle read-ready event on a connection */
static void handle_read(connection_t *c) {
while (1) {
if (c->rlen >= sizeof(c->rbuf) - 1) {
send_error(c, "request too long");
return;
}
ssize_t n = read(c->fd, c->rbuf + c->rlen,
sizeof(c->rbuf) - 1 - c->rlen);
if (n == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
break; /* all data read */
perror("read");
close_connection(c);
return;
} else if (n == 0) {
/* client closed */
close_connection(c);
return;
} else {
c->rlen += (size_t)n;
c->rbuf[c->rlen] = '\0';
/* Simple model: process first complete line, then stop */
char *newline = memchr(c->rbuf, '\n', c->rlen);
if (newline) {
process_request(c);
return;
}
}
}
}
/* Handle write-ready event on a connection */
static void handle_write(connection_t *c) {
while (c->wpos < c->wlen) {
ssize_t n = write(c->fd, c->wbuf + c->wpos, c->wlen - c->wpos);
if (n == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return; /* can't write more now */
perror("write");
close_connection(c);
return;
} else if (n == 0) {
/* Shouldn't normally happen */
break;
} else {
c->wpos += (size_t)n;
}
}
if (c->wpos >= c->wlen) {
/* Done sending response; close connection */
close_connection(c);
}
}
/* Worker thread main loop */
static void *worker_main(void *arg) {
worker_t *w = (worker_t *)arg;
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = w->notify_receive_fd;
if (epoll_ctl(w->epfd, EPOLL_CTL_ADD, w->notify_receive_fd, &ev) == -1) {
perror("epoll_ctl ADD notify");
return NULL;
}
struct epoll_event events[MAX_EVENTS];
for (;;) {
int n = epoll_wait(w->epfd, events, MAX_EVENTS, -1);
if (n == -1) {
if (errno == EINTR)
continue;
perror("epoll_wait");
break;
}
for (int i = 0; i < n; ++i) {
struct epoll_event *e = &events[i];
if (e->data.fd == w->notify_receive_fd) {
/* New client fds from main thread */
while (1) {
int client_fd;
ssize_t r = read(w->notify_receive_fd,
&client_fd, sizeof(client_fd));
if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
break;
perror("read from notify pipe");
break;
} else if (r == 0) {
/* pipe closed; shutdown? */
break;
} else if (r == sizeof(client_fd)) {
if (make_nonblocking(client_fd) == -1) {
close(client_fd);
continue;
}
connection_t *c = calloc(1, sizeof(*c));
if (!c) {
fprintf(stderr, "calloc connection failed\n");
close(client_fd);
continue;
}
c->fd = client_fd;
c->worker = w;
c->state = STATE_READING;
c->rlen = 0;
c->wbuf = NULL;
c->wlen = 0;
c->wpos = 0;
struct epoll_event cev;
cev.events = EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR;
cev.data.ptr = c;
if (epoll_ctl(w->epfd, EPOLL_CTL_ADD, client_fd, &cev) == -1) {
perror("epoll_ctl ADD client");
close(client_fd);
free(c);
continue;
}
} else {
/* partial read of int; shouldn't happen with non-blocking pipe and sizeof(int) writes */
break;
}
}
} else {
connection_t *c = (connection_t *)e->data.ptr;
uint32_t evts = e->events;
if (evts & (EPOLLHUP | EPOLLERR | EPOLLRDHUP)) {
close_connection(c);
continue;
}
if (c->state == STATE_READING && (evts & EPOLLIN)) {
handle_read(c);
} else if (c->state == STATE_WRITING && (evts & EPOLLOUT)) {
handle_write(c);
}
}
}
}
return NULL;
}
/* Create listening socket */
static int create_listen_socket(int port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
perror("socket");
return -1;
}
int opt = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
perror("setsockopt SO_REUSEADDR");
close(fd);
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons((uint16_t)port);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind");
close(fd);
return -1;
}
if (listen(fd, SOMAXCONN) == -1) {
perror("listen");
close(fd);
return -1;
}
return fd;
}
/* Initialize worker threads and their epoll instances */
static int init_workers(int nworkers) {
for (int i = 0; i < nworkers; ++i) {
worker_t *w = &g_workers[i];
w->id = i;
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
return -1;
}
w->notify_receive_fd = pipefd[0];
w->notify_send_fd = pipefd[1];
if (make_nonblocking(w->notify_receive_fd) == -1 ||
make_nonblocking(w->notify_send_fd) == -1) {
return -1;
}
w->epfd = epoll_create1(0);
if (w->epfd == -1) {
perror("epoll_create1");
return -1;
}
if (pthread_create(&w->thread, NULL, worker_main, w) != 0) {
perror("pthread_create");
return -1;
}
}
return 0;
}
/* Dispatch a client FD to a worker (round-robin) */
static void dispatch_to_worker(int client_fd) {
static int next_worker = 0;
worker_t *w = &g_workers[next_worker];
next_worker = (next_worker + 1) % g_num_workers;
ssize_t n = write(w->notify_send_fd, &client_fd, sizeof(client_fd));
if (n != sizeof(client_fd)) {
/* If we fail to enqueue, just close the client socket */
if (n == -1)
perror("write to worker pipe");
close(client_fd);
}
}
int main(int argc, char **argv) {
int port = DEFAULT_PORT;
if (argc >= 2)
port = atoi(argv[1]);
if (argc >= 3)
g_docroot = argv[2];
printf("Starting server on port %d, docroot: %s\n", port, g_docroot);
/* Ignore SIGPIPE so writes to closed sockets don't crash the process */
signal(SIGPIPE, SIG_IGN);
if (init_workers(g_num_workers) == -1) {
fprintf(stderr, "Failed to initialize workers\n");
return 1;
}
int listen_fd = create_listen_socket(port);
if (listen_fd == -1)
return 1;
/* Accept loop */
for (;;) {
struct sockaddr_in in_addr;
socklen_t in_len = sizeof(in_addr);
int client_fd = accept(listen_fd, (struct sockaddr *)&in_addr, &in_len);
if (client_fd == -1) {
if (errno == EINTR)
continue;
perror("accept");
break;
}
dispatch_to_worker(client_fd);
}
close(listen_fd);
/* In a real server you would signal workers to exit and join them. */
return 0;
}
Build and run
gcc -Wall -Wextra -O2 -pthread epoll_file_server.c -o epoll_file_server
./epoll_file_server 9000 /path/to/docroot
If you omit arguments, it defaults to port 9000 and docroot ".".
Testing
From another terminal, in the docroot directory:
echo "Hello world" > hello.txt
nc 127.0.0.1 9000
GET hello.txt
You should see something like:
OK 12
Hello world
For a missing file:
GET does_not_exist
ERR file not found
This example is intentionally minimal but shows:
- Multi-threading with
pthread.
- Per-thread
epoll-based I/O handling.
- A simple request/response file-serving protocol.
For production use, you’d want more robust error handling, better shutdown logic, path sanitization, and possibly support for persistent connections or HTTP.