Skip to content

Instantly share code, notes, and snippets.

@et4te
Created December 12, 2018 01:29
Show Gist options
  • Save et4te/85f6b66f3c04404be392cdf83cd4fc44 to your computer and use it in GitHub Desktop.
Save et4te/85f6b66f3c04404be392cdf83cd4fc44 to your computer and use it in GitHub Desktop.
Times out if can't read
open Lwt
open Lwt_unix
let read fd =
let maxlen = 1024 in
let buf = Bytes.create maxlen in
Lwt.catch
(fun _ ->
Lwt_log.info "reading" >>= fun () ->
Lwt.pick [
Lwt_unix.timeout 1.0;
Lwt_unix.read fd buf 0 maxlen
] >>= fun len ->
if len = 0
then Lwt_log.info "len = 0"
else Lwt_log.info "got some bytes")
(fun _ -> Lwt_log.info "got an error")
let connect fd =
ignore(Lwt_unix.connect fd @@ ADDR_INET(Unix.inet_addr_of_string "172.217.195.113", 80));
read fd >>= fun _ ->
Lwt.return 0
let () =
let fd = Lwt_unix.socket PF_INET SOCK_STREAM 0 in
Pervasives.exit (Lwt_main.run (connect fd))
@et4te
Copy link
Author

et4te commented Dec 12, 2018

Compile with ocamlfind ocamlopt -package lwt.unix -package lwt_log -linkpkg -g timeout.ml -o timeout_test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment