From b2b637041b1b797e5a51928954b6fc3bd6c04ce5 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 4 Dec 2023 15:45:18 -0500 Subject: [PATCH] fix: do not block in `accept` --- src/Tiny_httpd_server.ml | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/Tiny_httpd_server.ml b/src/Tiny_httpd_server.ml index 94347fe7..d6757725 100644 --- a/src/Tiny_httpd_server.ml +++ b/src/Tiny_httpd_server.ml @@ -937,11 +937,14 @@ module Unix_tcp_server_ = struct () in + Unix.set_nonblock sock; while self.running do - (* limit concurrency *) - Sem_.acquire 1 self.sem_max_connections; - try - let client_sock, client_addr = Unix.accept sock in + ignore (Unix.select [ sock ] [] [ sock ] 1.0 : _ * _ * _); + match Unix.accept sock with + | client_sock, client_addr -> + (* limit concurrency *) + Sem_.acquire 1 self.sem_max_connections; + Unix.setsockopt client_sock Unix.TCP_NODELAY true; (* Block INT/HUP while cloning to avoid children handling them. When thread gets them, our Unix.accept raises neatly. *) @@ -955,8 +958,10 @@ module Unix_tcp_server_ = struct Sem_.release 1 self.sem_max_connections; raise e); ignore Unix.(sigprocmask SIG_UNBLOCK Sys.[ sigint; sighup ]) - with e -> - Sem_.release 1 self.sem_max_connections; + | exception Unix.Unix_error ((Unix.EAGAIN | Unix.EWOULDBLOCK), _, _) + -> + () + | exception e -> _debug (fun k -> k "Unix.accept or Thread.create raised an exception: %s" (Printexc.to_string e))