networking · advanced · ~18 min · safe pentest lab

Multi-client server with threads (3 connections)

One-thread-per-connection pattern with pthread_detach.

Challenge

Serve several clients at once using the simplest concurrency model: one thread per connection.

Task

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

  1. Accepts n clients, one after another.
  2. For each accepted fd, spawns a detached thread (via pthread_detach) that echoes the client's bytes back and then closes that fd.
  3. Returns as soon as all n accepts have been issued — it does NOT wait for the worker threads to finish.

Input

  • listening_fd: an already-bound, already-listening TCP socket (the grader opens it on 127.0.0.1).
  • n: the number of clients to accept.

Output

Return 0 on success (all n accepts issued and threads spawned), or -1 on failure.

Example

3 clients each connect and send one byte
  -> serve_n_threads(fd, 3) returns 0, and every client reads its byte echoed back

Rules

  • Use pthread_detach so threads clean themselves up — do not join them.
  • Do not block waiting for the workers; return once all n connections are accepted.

Why this matters

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

Input format

listening_fd: a bound, listening TCP socket on 127.0.0.1; n: number of clients to accept.

Output format

0 on success (all n accepts issued, threads spawned), -1 on failure.

Constraints

One detached thread per accepted connection; do not join; return without waiting for workers to finish.

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.