App doesn't respond to Ctrl-C / SIGINT / Signals when running dune exec

I’m new to OCaml and have been struggling to set up a simple TCP server that stays open and can be killed or interrupted with Ctrl-C. Here's where I'm at withLwt_io.establish_server_with_client_address`:

let establish_server port f =
  (* Create a new socket *)
  let default_protocol = 0 in
  let socket = Lwt_unix.socket PF_INET SOCK_STREAM default_protocol in
  let _ = Lwt_unix.setsockopt socket SO_REUSEADDR true in

  (* Create a socket address *)
  let host = Unix.inet_addr_loopback in
  let addr = Unix.ADDR_INET (host, port) in

  (* Start server *)
  let max_pending_requests = 10 in
  let server = Lwt_io.establish_server_with_client_address
    ~backlog:max_pending_requests
    ~fd:socket
    addr
    f; in
  server

let service _client_address (_in_channel, _out_channel) =
  let%lwt _ = Lwt_io.eprintf "TODO ;)\n%!"; in
  Lwt.return ()

let () =
  Lwt_main.run begin
    let port = 8080 in
    let%lwt _ = establish_server port service; in

    (* ??? 
    Lwt.return () // <-- This will close immediately without keeping the server open
    fst (Lwt.task ())  // <-- this can't be cancelled with Ctrl-C
    *)
  end

@seanpoulter I am able to terminate the program with Ctrl+C with fst (Lwt.task ()) uncommented. What environment are you running this in (shell, OS, anything else noteworthy)?

Thanks @antron. I think I’ve worked it out to be ocaml/dune#1480.

I’ve got a Macbook that I’ve recently setup with dune 1.4.0. I’ve narrowed it down to only happening when I run:

dune exec ./main.exe

It responds to Ctrl-c when I run:

dune build ./file.exe
_build/default/file.exe

You may have already done this, but try upgrading to Dune 1.5.0. It fixed:

Unblock signals in processes started by dune (link)

Yea, thanks. It was just realizing that you had to opam update before opam is aware of the new versions. I had tried opam install dune and opam upgrade dune and kept 1.4.0. :laughing:

Thanks for the help and nudge in the right direction! :clap:

1 Like