Signals in OCaml

Here’s the translation of the Go code to OCaml, with explanations in Markdown format suitable for Hugo:

Our program demonstrates how to handle Unix signals in OCaml. We’ll use the Sys module to handle signals and the Lwt library for concurrent programming.

open Lwt
open Lwt.Infix

let handle_signal signum =
  let () = print_endline "" in
  let sig_name = Sys.signal_name signum in
  let () = Printf.printf "Received signal: %s\n" sig_name in
  Lwt.return_unit

let main () =
  let sigint = Lwt_unix.on_signal Sys.sigint handle_signal in
  let sigterm = Lwt_unix.on_signal Sys.sigterm handle_signal in

  let () = print_endline "Awaiting signal" in
  
  Lwt.pick [sigint; sigterm] >>= fun () ->
  
  let () = print_endline "Exiting" in
  Lwt.return_unit

let () = Lwt_main.run (main ())

In this OCaml program:

  1. We use the Lwt library for concurrent programming, which is similar to goroutines in concept.

  2. The handle_signal function is called when a signal is received. It prints the name of the signal.

  3. In the main function, we set up signal handlers for SIGINT and SIGTERM using Lwt_unix.on_signal.

  4. We use Lwt.pick to wait for either of these signals to occur.

  5. Once a signal is received and handled, the program prints “Exiting” and terminates.

To run this program:

$ ocamlbuild -pkg lwt.unix signal_example.native
$ ./signal_example.native
Awaiting signal
^C
Received signal: int
Exiting

In this example, we use Ctrl-C to send a SIGINT signal, causing the program to print the signal name and then exit.

This OCaml implementation provides similar functionality to the original example, demonstrating how to handle signals in a concurrent context using OCaml and the Lwt library.