Lwt_main.run p calls the Lwt scheduler, performing I/O until p resolves. Lwt_main.run p returns the value in p if p is fulfilled. If p is rejected with an exception instead, Lwt_main.run p raises that exception.
Every native and bytecode program that uses Lwt should call this function at its top level. It implements the Lwt main loop.
Example:
let main () = Lwt_io.write_line Lwt_io.stdout "hello world"
let () = Lwt_main.run (main ())
Lwt_main.run is not available when targeting JavaScript, because the environment (such as Node.js or the browser's script engine) implements the I/O loop.
On Unix, calling Lwt_main.run installs a SIGCHLD handler, which is needed for the implementations of Lwt_unix.waitpid and Lwt_unix.wait4. As a result, programs that call Lwt_main.run and also use non-Lwt system calls need to handle those system calls failing with EINTR.
Nested calls to Lwt_main.run are not allowed. That is, do not call Lwt_main.run in a callback triggered by a promise that is resolved by an outer invocation of Lwt_main.run. If your program makes such a call, Lwt_main.run will raise Failure. This should be considered a logic error (i.e., code making such a call is inherently broken).
In addition, note that if you have set the exception filter to let runtime exceptions bubble up (via Lwt.Exception_filter.(set handle_all_except_runtime)) then Lwt does not attempt to catch exceptions thrown by the OCaml runtime. Specifically, in this case, Lwt lets Out_of_memory and Stack_overflow exceptions traverse all of its functions and bubble up to the caller of Lwt_main.run. Moreover because these exceptions are left to traverse the call stack, they leave the internal data-structures in an inconsistent state. For this reason, calling Lwt_main.run again after such an exception will raise Failure.
It is not safe to call Lwt_main.run in a function registered with Stdlib.at_exit, use Lwt_main.at_exit instead.