Question

I have written some code in OCaml which performs actions similar to the following

    let rec main() = 

      DO STUFF...

      let print_time() = 
        let time = Unix.localtime (Unix.time()) in
        let hour = string_of_int (time.Unix.tm_hour) in
        let minute = string_of_int (time.Unix.tim_min) in
        print_string ("\n Time -- " ^ hour ^ ":" ^ minute)
      in

      Lwt.bind(Lwt_unix.sleep 30.)
      (fun() -> (print_time(); main();)
    ;;

    main();;

This code runs perfectly in the toplevel, however it seems that the times are being printed to a buffer and not immediately printed to the screen. All of the times in the buffer print to the screen at once when I give the toplevel another command.

How can I correct this issue so that the times are printed to the toplevel every time print_time() is called and not when I give the toplevel a command?

Example: If I run the program and then wait 2 minutes before I type something into the toplevel I get the following output. If I don't type anything into the toplevel then I only receive the first time message.

    # #use "this_program";;
    Time -- 12:03

    # let x = 1;;
    time -- 12:03
    time -- 12:04
    time -- 12:04
    time -- 12:05
    time -- 12:05
    val x : int = 1
    #

Also, this "loop" only works once (main() will not recursively call itself) in native compiled code, I have no idea how to correct that.

Was it helpful?

Solution

I would try adding flush stdout after your call to print_string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top