Skip to content

Commit 76cefc0

Browse files
committed
cleanup for lwt
1 parent 3014046 commit 76cefc0

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

src/lwt/tiny_httpd_lwt.ml

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ let io_backend ?addr ?port ?unix_sock ?max_connections ?max_buf_pool_size
129129
Lwt_unix.bind sock sockaddr |> Lwt_direct.await;
130130
Lwt_unix.listen sock backlog;
131131

132+
let cleanup () = Lwt_unix.close sock |> Lwt_direct.await in
133+
132134
(* recover real port, if any *)
133135
(match Unix.getsockname (Lwt_unix.unix_file_descr sock) with
134136
| Unix.ADDR_INET (_, p) -> port := p
@@ -137,12 +139,6 @@ let io_backend ?addr ?port ?unix_sock ?max_connections ?max_buf_pool_size
137139
let handle_client client_addr fd : unit =
138140
Atomic.incr active_conns;
139141
Lwt_direct.run_in_the_background @@ fun () ->
140-
let cleanup () =
141-
Log.debug (fun k ->
142-
k "Tiny_httpd_lwt: client handler returned");
143-
Atomic.decr active_conns
144-
in
145-
146142
let buf_ic = Bytes.create buf_size in
147143
let buf_oc = Bytes.create buf_size in
148144
(*
@@ -154,6 +150,16 @@ let io_backend ?addr ?port ?unix_sock ?max_connections ?max_buf_pool_size
154150
let num_open = ref 2 in
155151
let ic = ic_of_fd ~num_open ~bytes:buf_ic fd in
156152
let oc = oc_of_fd ~num_open ~bytes:buf_oc fd in
153+
154+
let cleanup () =
155+
Log.debug (fun k ->
156+
k "Tiny_httpd_lwt: client handler returned");
157+
Atomic.decr active_conns;
158+
(try Lwt_unix.shutdown fd SHUTDOWN_ALL with _ -> ());
159+
ic#close ();
160+
oc#close ()
161+
in
162+
157163
try
158164
handle.handle ~client_addr ic oc;
159165
cleanup ()
@@ -167,10 +173,16 @@ let io_backend ?addr ?port ?unix_sock ?max_connections ?max_buf_pool_size
167173
(Printexc.raw_backtrace_to_string bt))
168174
in
169175

170-
while Atomic.get running do
171-
let fd, addr = Lwt_unix.accept sock |> Lwt_direct.await in
172-
handle_client addr fd
173-
done
176+
try
177+
while Atomic.get running do
178+
let fd, addr = Lwt_unix.accept sock |> Lwt_direct.await in
179+
handle_client addr fd
180+
done;
181+
cleanup ()
182+
with exn ->
183+
let bt = Printexc.get_raw_backtrace () in
184+
cleanup ();
185+
Printexc.raise_with_backtrace exn bt
174186
in
175187

176188
let tcp_server : IO.TCP_server.t =

0 commit comments

Comments
 (0)