networking · advanced · ~18 min · safe pentest lab

Multi-client server with threads (3 connections)

One-thread-per-connection pattern with pthread_detach.

Challenge

Implement int serve_n_threads(int listening_fd, int n) that:

  1. Accepts n clients sequentially.
  2. For each accepted fd, spawns a detached thread that runs an echo loop on that fd, then closes it.
  3. Returns 0 on success. The function should NOT wait for the threads to finish — return as soon as all n accepts have been issued.

Use pthread_detach so you don't have to join the threads explicitly.

Why this matters

The simplest concurrency model for a server: one thread per connection.

Starter code

#include <pthread.h>
#include <sys/socket.h>
#include <unistd.h>
int serve_n_threads(int listening_fd, int n) {
    /* TODO */
    return -1;
}

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.