Develop a multi-threaded file server in C using the thread pool pattern with edge-triggered epoll. The main thread accepts connections and adds file descriptors to epoll, while worker threads pull ready events and do non-blocking I/O.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Designing epoll edge-triggered thread pool architecture
The plan is a main thread running epoll_wait to accept new connections and push other ready events into a thread-safe queue, while worker threads pull from that queue to perform non-blocking I/O handling, ensuring full socket draining per edge-triggered semantics and coordinating concurrency safely.Providing complete multi-threaded epoll edge-triggered file server code
The full C code implements a main thread accepting connections and running epoll_wait to dispatch ready connection events into a thread-safe queue, with worker threads pulling events to perform non-blocking reads (treating input as file paths) and sending file content, demonstrating edge-triggered epoll with a thread pool pattern.
Below is a self–contained example of how you can combine an edge–triggered epoll(7) instance with a fixed–size pool of worker threads to build a simple “file server” that accepts a connection, reads a path terminated by a newline, and sends back the file contents. The main thread is responsible for creating the listening socket, accepting new connections, and registering them with epoll in edge–triggered mode; it dispatches ready events into a thread‑safe queue. Worker threads pull events from the queue and perform non–blocking I/O until EAGAIN.
This is meant as a skeleton to illustrate the pattern rather than a production‑ready server. In particular, it assumes each client sends a single, small request; if you need to support arbitrary request sizes or multiple requests per connection you should maintain per–connection state and handle partial reads/writes properly.
c
#define _GNU_SOURCE
#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/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define LISTEN_PORT 8080
#define MAX_EVENTS 1024
#define WORKER_THREADS 4
#define MAX_PATH_LEN 1024
#define FILE_BUF_SIZE 8192
typedef struct {
int fd;
uint32_t events;
} work_item_t;
typedef struct {
work_item_t items[MAX_EVENTS];
int head;
int tail;
int count;
pthread_mutex_t mutex;
pthread_cond_t cond;
} work_queue_t;
static int epoll_fd;
static work_queue_t queue;
static void queue_init(work_queue_t *q) {
q->head = q->tail = q->count = 0;
pthread_mutex_init(&q->mutex, NULL);
pthread_cond_init(&q->cond, NULL);
}
static void queue_push(work_queue_t *q, work_item_t item) {
pthread_mutex_lock(&q->mutex);
while (q->count == MAX_EVENTS) {
/* queue full, wait */
pthread_cond_wait(&q->cond, &q->mutex);
}
q->items[q->tail] = item;
q->tail = (q->tail + 1) % MAX_EVENTS;
q->count++;
pthread_cond_signal(&q->cond);
pthread_mutex_unlock(&q->mutex);
}
static work_item_t queue_pop(work_queue_t *q) {
pthread_mutex_lock(&q->mutex);
while (q->count == 0) {
pthread_cond_wait(&q->cond, &q->mutex);
}
work_item_t item = q->items[q->head];
q->head = (q->head + 1) % MAX_EVENTS;
q->count--;
pthread_cond_signal(&q->cond);
pthread_mutex_unlock(&q->mutex);
return item;
}
static int set_nonblock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
return -1;
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
return -1;
return 0;
}
static void handle_client(int fd) {
char path[MAX_PATH_LEN];
ssize_t n;
/* Edge–triggered: loop until EAGAIN */
for (;;) {
n = read(fd, path, sizeof(path) - 1);
if (n > 0) {
path[n] = '\0';
/* trim trailing newline */
char *nl = strpbrk(path, "\r\n");
if (nl)
*nl = '\0';
int file_fd = open(path, O_RDONLY);
if (file_fd < 0) {
const char *msg = "ERROR: cannot open file\n";
(void)write(fd, msg, strlen(msg));
} else {
char fbuf[FILE_BUF_SIZE];
ssize_t r;
while ((r = read(file_fd, fbuf, sizeof(fbuf))) > 0) {
ssize_t off = 0;
while (off < r) {
ssize_t w = write(fd, fbuf + off, r - off);
if (w < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* would block; in a real server you'd rearm EPOLLOUT
and remember how much is left to send */
continue;
} else {
perror("write");
close(file_fd);
close(fd);
return;
}
}
off += w;
}
}
close(file_fd);
}
/* for this simple example, close connection after one request */
close(fd);
return;
} else if (n == 0) {
/* peer closed */
close(fd);
return;
} else {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* all data consumed for now */
return;
} else {
perror("read");
close(fd);
return;
}
}
}
}
static void *worker_main(void *arg) {
(void)arg;
for (;;) {
work_item_t item = queue_pop(&queue);
if (item.fd == -1) { /* shutdown sentinel */
break;
}
if (item.events & (EPOLLERR | EPOLLHUP)) {
fprintf(stderr, "EPOLLERR/EPOLLHUP on fd %d\n", item.fd);
close(item.fd);
continue;
}
if (item.events & EPOLLIN) {
handle_client(item.fd);
/* If keeping the connection open, you might need to rearm interest here. */
}
}
return NULL;
}
int main(void) {
int listen_fd;
struct sockaddr_in addr;
signal(SIGPIPE, SIG_IGN);
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
int yes = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(LISTEN_PORT);
if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
close(listen_fd);
exit(EXIT_FAILURE);
}
if (set_nonblock(listen_fd) < 0) {
perror("set_nonblock");
close(listen_fd);
exit(EXIT_FAILURE);
}
if (listen(listen_fd, SOMAXCONN) < 0) {
perror("listen");
close(listen_fd);
exit(EXIT_FAILURE);
}
epoll_fd = epoll_create1(0);
if (epoll_fd < 0) {
perror("epoll_create1");
close(listen_fd);
exit(EXIT_FAILURE);
}
struct epoll_event ev;
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = listen_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev) < 0) {
perror("epoll_ctl listen_fd");
close(listen_fd);
close(epoll_fd);
exit(EXIT_FAILURE);
}
queue_init(&queue);
pthread_t workers[WORKER_THREADS];
for (int i = 0; i < WORKER_THREADS; ++i) {
if (pthread_create(&workers[i], NULL, worker_main, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
struct epoll_event events[MAX_EVENTS];
printf("Listening on port %d\n", LISTEN_PORT);
for (;;) {
int nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
if (nfds < 0) {
if (errno == EINTR)
continue;
perror("epoll_wait");
break;
}
for (int i = 0; i < nfds; ++i) {
if (events[i].data.fd == listen_fd) {
/* New incoming connection(s); accept until EAGAIN */
for (;;) {
struct sockaddr_in cli;
socklen_t clilen = sizeof(cli);
int conn_fd = accept(listen_fd, (struct sockaddr *)&cli, &clilen);
if (conn_fd < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
break;
perror("accept");
break;
}
set_nonblock(conn_fd);
struct epoll_event cev;
cev.events = EPOLLIN | EPOLLET;
cev.data.fd = conn_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, conn_fd, &cev) < 0) {
perror("epoll_ctl conn_fd");
close(conn_fd);
}
}
} else {
/* Dispatch ready client fd to a worker thread */
work_item_t item = {.fd = events[i].data.fd, .events = events[i].events};
queue_push(&queue, item);
}
}
}
/* shutdown */
for (int i = 0; i < WORKER_THREADS; ++i) {
work_item_t stop = {.fd = -1, .events = 0};
queue_push(&queue, stop);
}
for (int i = 0; i < WORKER_THREADS; ++i)
pthread_join(workers[i], NULL);
close(listen_fd);
close(epoll_fd);
return 0;
}
A few things to note about this pattern:
All sockets are set non‑blocking, and both the listening socket and client sockets are registered with EPOLLET to get edge–triggered semantics. That means you must accept in a loop until EAGAIN, and you must read/write until EAGAIN in your handlers.
Only the main thread calls epoll_wait(). It pushes work items into a protected queue. Workers never touch the epoll file descriptor; they just perform I/O on the ready file descriptors they pop.
In a more complete server you would maintain per‑connection state (buffers, how much has been sent, etc.) and rearm interest with epoll_ctl/EPOLLONESHOT as needed if you need to handle partial writes.