POSIX signals as Eio events
README.md

eio-signal #

POSIX signals as Eio events.

Hitting ^C on a tool that has started a VM, or holds a session open, should unwind it and free what it holds. It should not kill it mid-flight.

Doing that under Eio is harder than it looks. A Sys.signal handler runs at the next allocation or poll point, which can be in the middle of the scheduler updating its run queues, so the handler cannot touch scheduler state and cannot resume a blocked fiber directly. What it can do is write a byte to a pipe: one system call, no shared state, and the scheduler already knows how to wait on a file descriptor.

Eio_signal is that self-pipe trick, scoped. install puts handlers in place for the duration of a function, the first signal becomes an Eio event that wakes the waiting fiber through the scheduler, and the old handlers are put back on exit.

Installation #

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam install eio-signal

Usage #

To run until interrupted, race the scope's work against the latch:

let watch_until_interrupted (follow : unit -> (unit, string) result) =
  Eio_signal.install @@ fun stop ->
  Eio.Fiber.first
    (fun () ->
      Eio_signal.await stop;
      Ok ())
    follow

A loop that checks between steps, without blocking, can poll Eio_signal.requested instead. The latch does not say which signal arrived; code that needs to know, or that must act inside the handler, should call Eio_unix.set_signal itself, which unlike Sys.set_signal wakes the scheduler for a signal that lands as it goes to sleep.

An OCaml handler runs at the runtime's next safe point, and a scheduler asleep in poll(2) reaches one only when that call returns. A signal that lands just before the call starts would wait for the next unrelated wake, so the latch's handler writes its pipe from C before the runtime records the signal.

OCaml numbers signals with negative integers that are the same on every platform, while the operating system has its own numbers. The eio-signal.posix library converts between the two. Posix_signal.exit_code turns a process status into the shell's exit code, so SIGINT gives 130.

Licence #

ISC. See LICENSE.md.