networking · advanced · ~18 min · safe pentest lab
One-thread-per-connection pattern with pthread_detach.
Serve several clients at once using the simplest concurrency model: one thread per connection.
Implement int serve_n_threads(int listening_fd, int n) that:
n clients, one after another.pthread_detach) that echoes the client's bytes back and then closes that fd.n accepts have been issued — it does NOT wait for the worker threads to finish.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.Return 0 on success (all n accepts issued and threads spawned), or -1 on failure.
3 clients each connect and send one byte
-> serve_n_threads(fd, 3) returns 0, and every client reads its byte echoed back
pthread_detach so threads clean themselves up — do not join them.n connections are accepted.The simplest concurrency model for a server: one thread per connection.
listening_fd: a bound, listening TCP socket on 127.0.0.1; n: number of clients to accept.
0 on success (all n accepts issued, threads spawned), -1 on failure.
One detached thread per accepted connection; do not join; return without waiting for workers to finish.
#include <pthread.h>
#include <sys/socket.h>
#include <unistd.h>
int serve_n_threads(int listening_fd, int n) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.