Start a program in a session of its own without forking the caller (posix_spawn SETSID)
README.md

daemon #

Start a program in a session of its own, without forking the caller.

Daemon.spawn starts an executable as the leader of a new session and process group with no controlling terminal, so it survives the caller's exit, the caller's process group being signalled, and the caller's terminal going away. The child comes from posix_spawn(3) with POSIX_SPAWN_SETSID, or from vfork(2) and execve(2) where that call cannot keep the caller's other descriptors out of the child, so the caller is never duplicated. A domain is OCaml 5's unit of parallelism: a system thread with its own minor heap that runs OCaml code in parallel with the others. fork(2) copies only the calling thread, so a child forked while another domain runs could inherit the heap or a lock in the middle of that domain's update; OCaml 5's Unix.fork therefore fails for the rest of a process's life once any domain has been spawned, and duplicating a multi-threaded runtime is a hazard where it is still allowed.

Requires OCaml >= 5.1. Supported on macOS and on Linux, the platforms which can keep the caller's other descriptors out of the child.

Security #

  • The child receives the three descriptors it is given as its standard input, output and error, plus explicitly declared extra_fds, and no others, whatever the close-on-exec state of the caller's descriptors and whatever another domain opens while the call runs. Each mechanism settles the set to close in the child, whose descriptor table is the copy taken when it was made: POSIX_SPAWN_CLOEXEC_DEFAULT on macOS, posix_spawn_file_actions_addclosefrom_np on glibc 2.34 and later, and close_range(2) between a vfork(2) and the execve(2) on any other Linux libc, where posix_spawn has no file action which closes a range and no hook for one. A platform with none of the three fails to build rather than spawn something less confined.
  • Signal dispositions are reset to default and the signal mask emptied, so an ignored or blocked signal in the caller does not silently disable the same signal in the new program.
  • A string carrying a NUL byte is refused before anything reaches the C boundary, where it would be read as the end of a shorter argument than the caller wrote.
  • The child is a session leader with no controlling terminal, so it cannot be reached by a terminal's job-control signals and cannot acquire the caller's terminal.

Install #

$ opam install daemon

If opam cannot find the package, add the overlay repository first:

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

Usage #

(* Start a launcher which outlives this process, with its output in a log. *)
let start ~log exe =
  let input = Unix.openfile "/dev/null" [ Unix.O_RDONLY ] 0 in
  let output =
    Unix.openfile (Fpath.to_string log)
      [ Unix.O_WRONLY; Unix.O_CREAT; Unix.O_APPEND ]
      0o600
  in
  let started =
    Daemon.spawn ~stdin:input ~stdout:output ~stderr:output exe
      [ Fpath.to_string exe; "--serve" ]
  in
  (* The child has its own copies; these are the caller's. *)
  Unix.close input;
  Unix.close output;
  match started with
  | Ok pid -> Fmt.pr "launcher running as pid %d@." pid
  | Error (`Msg message) -> prerr_endline message

API #

  • Daemon.spawn ?cwd ?env ~stdin ~stdout ~stderr exe argv starts exe with the whole argument vector argv (its head is argv.(0)) and is its pid. cwd is the child's working directory, the caller's by default; env is the child's whole environment as KEY=VALUE bindings, the caller's by default. A program which cannot be executed (ENOENT, EACCES, ENOEXEC) is an error returned by the call, and no child is left to exit with 127. No exception escapes.
  • Daemon.wait_exited pid waits for the pid spawn returned to end, and is how it ended, without reaping it, so a caller that has killed the process group pid still names (Daemon.signal_group) can do so before the number is freed by a reap, then reap the leader itself with Daemon.reap.
  • Daemon.Signal.with_target ~pid f holds a process by its kernel identity while f checks Daemon.Signal.start_us target against its intended start and sends with Daemon.Signal.send target signal. Linux uses a pidfd; Darwin uses the pid version in an audit token. A reused pid receives no signal, and a target retained after f ends refuses every send.
  • Daemon.Waker.start wake forks a waker, in C, its child making only async-signal-safe calls: once the caller ends without Daemon.Waker.settle, it creates wake's files and runs its commands, so a process that holds a lock with no supervisor still tells a watcher the lock is free after a KILL.

See lib/daemon.mli for the full documentation.

From Eio #

daemon.eio is the same call over Eio flows. Daemon_eio.spawn unwraps the descriptor behind each flow for the duration of the call, so a program which opens its log through an Eio.Path capability never handles a descriptor itself. A stream not given is /dev/null, opened for the call and closed once the child holds its copy. A flow with no descriptor to give (a buffer, a mock, a TLS flow) is refused before anything is spawned. The descriptor a flow carries is put in blocking mode first, since the child's copy shares the flag and the eio_posix backend opens every file and both ends of a pipe with O_NONBLOCK (eio_linux, only its pipes). It stays cleared afterwards, spawn or no spawn: giving the flag back would give it back to the child.

(* The same launcher, its console opened through an Eio capability. *)
let start_eio ~sw ~log exe =
  let console =
    Eio.Path.open_out ~sw ~append:true ~create:(`If_missing 0o600) log
  in
  match
    Daemon_eio.spawn ~stdout:console ~stderr:console exe
      [ Fpath.to_string exe; "--serve" ]
  with
  | Ok pid -> Fmt.pr "launcher running as pid %d@." pid
  | Error e -> Fmt.epr "%a@." Daemon_eio.pp_error e

Daemon_eio.wait_exited pid is Daemon.wait_exited from a fiber. The pure call is a blocking waitid(2) and holds the whole domain, every other fiber and timer included, for as long as the child lives. This one runs it on a system thread, so only the calling fiber waits. It leaves the child unreaped just the same, and cannot be cancelled once the wait has begun. Daemon_eio.reap pid is Daemon.reap on a system thread in the same way, for a caller with no group to signal between the end and the reap.

Daemon_eio.copy_logged ~lost ~log src sink keeps a process stream in its log before forwarding each chunk to an attached sink. A sink I/O failure sets lost and forwarding ends; the log receives the remaining stream in full.

Daemon_eio.Session.run mgr clock ?silence ~stdin ~out ~err argv runs a client command to its end, such as an SSH session, its two streams each folded as they come; a fold that refuses a chunk closes its stream, so the command's next write there fails. With silence, a command whose streams move no byte for that many seconds is killed and its end says so: a remote program that hangs while its server still answers keepalives ends there, and one that keeps saying what it waits on runs however long it runs.

See lib/eio/daemon_eio.mli for the full documentation.

The pure part #

daemon.core holds the decisions, with no process, lock or file: it links neither Eio, unix nor threads, so its cases run with a script of answers.

  • Daemon_core.Lease is a lease's record: what the work an exclusive flock(2) guards is, the process a stop signals, and the lines the work's owner adds; an empty file is a lease held with no record.
  • Daemon_core.Process is a process found with the number the kernel gives it (Daemon.unique_id), and the proof that its pid names it still.
  • Daemon_core.Stop is the stop of the work a lease guards as a step machine: TERM to the holder the record names, the release or the holder's end awaited, a lease handed over followed, the proof of what holds a lease its holder left, and the second step (KILL to the group by its anchor, then its keeper). The caller performs each action and answers it with an event.
  • Daemon_core.Launchd is a launchd job: the property list launchd reads (launchd.plist(5)), where it reads it, and the launchctl(1) commands that load, unload, start and read it, as values the caller writes and runs.

See lib/core/stop.mli for the full documentation.

Unix.create_process, Lwt_process and Eio.Process start a child in the caller's session and process group. Taking a new session on top of one of them means forking and calling setsid(2) in the child, which is the shape this library replaces: posix_spawn(3) asks the kernel for both at once, so the call is available to a process which has spawned a domain and needs no child of its own to run OCaml code.

License #

ISC. See LICENSE.md.

Owned process groups #

Daemon.Managed.run starts a bounded command under a supervisor that is the program itself: it starts the running executable again, which serves in Daemon.Managed.main. A program that runs a managed command therefore calls Daemon.Managed.main () before anything else, and ships as one executable: the supervisor always speaks the protocol of the program that started it, and nothing is looked for on PATH. The supervisor makes the group's anchor and the lease keeper with fork(2), so a command starts the executable once. No duration bounds a command: it runs until it ends, its owner ends, a lease's file loses its name or its supervisor is stopped. The supervisor waits by the host's awake clock (Daemon.Managed.awake, CLOCK_UPTIME_RAW on macOS), so a sleep of the host ends no wait early. Daemon_eio.Managed.run adds fiber cancellation: leaving the fiber closes its ownership pipe and joins cleanup. A group started with ~held:true begins its command only once its owner hands it over (Daemon.Managed.release), so what the owner writes first, such as a lease's record naming the supervisor, is there at the command's first instant; an owner that ends first ends a group whose command never ran. Abrupt owner exit also closes that pipe, so it does not depend on an OCaml finalizer.

The supervisor keeps a live process-group anchor until it sends TERM followed by KILL, then reaps the anchor. No timer sends the KILL: it follows the command's end, or a second stop (Daemon.Managed.kill, or a second TERM to the supervisor), so a dune sent TERM writes its build database however long that takes. It never signals a PID recovered from disk. An optional descriptor-owned lease stays in the supervisor until the group has stopped; commands do not inherit either the lease or the ownership pipe. A lease lasts only while its file has a name: once a lease's file is removed, as a directory removed under it removes it, no process can find the lease to read or stop the command, so the supervisor stops the group as at its owner's end, released or not. The kernel reports each name removed, so nothing reads the file on a clock. A group the kernel cannot terminate retains its guardian and lease. The protocol uses a bounded JSON outcome.

This manages cooperating process groups: a descendant that moves to a group of its own in the session, as dune puts each action in one, is sent TERM and KILL with the group, and a command which deliberately creates a new session needs an external security container. With ~session:true the command's session is its whole scope: DAEMON_SESSION names it in every process of it, so a nested Daemon.spawn or managed command leads a group of its own there instead of a session, and the stop reaches every process of the session, an orphan re-parented to pid 1 included, and every descendant that left it while its parent lived, reading the session again after the KILL until none is left. A supervisor that dies leaves the group to its anchor, which reads the end of file of a pipe only the supervisor writes, stops the group with TERM then KILL once the command has ended, and ends. A TERM sent to the anchor from outside is passed to the group, a second one kills the command, and the run reports how it ended.

An observer signals one process with Daemon.signal_process ~pid ~start_us ~signal. It refuses a pid whose start differs from the observed microsecond instant. The operation uses the scoped Daemon.Signal target, with the kernel binding held across the start check and send. A failure returns its reason and the pid.

What an owner leaves behind #

An owner that supervises none of its processes, as a test page dune runs or a test case is, must still end with none of them running. Daemon.Owned.find finds them where they are rather than from a record of their pids: each process of the owner's process group with each of their descendants in another group, each process standing in any of the owner's directories, where a process that left the group and the session with setsid(2) still stands, even if its directory has been removed, and each process whose executable is under one of them, where a daemon built in the owner's tree still runs once it has also left the directory. Each is named by its pid and the number the kernel gives it and no other process until it boots again (Daemon.unique_id), so a pid the system has since given to another process is never signalled. Daemon.Owned.stop stops them as a supervisor stops its group: TERM, then KILL once the second stop comes, never at an instant.

The daemon-owned command reaches both from a shell. A test page's EXIT trap runs daemon-owned stop --check --leader "$$" --dir "$PAGE", which names each process the page left on standard error, stops it and exits 1: those of the process group the page's shell leads, as dune makes one for each page, and those standing in its directory or running an executable under it. A shell that leads no process group is refused: its group is its caller's, shared with the caller's other children. A page killed before its trap leaves its trap unrun, so the page also starts daemon-owned guard --dir "$PAGE" first: a watcher in a session of its own that waits for the page's shell to end, however it ends, then stops the same processes.

$ daemon-owned guard --dir "$PWD"
$ trap 'daemon-owned stop --check --leader "$$" --dir "$PWD"' EXIT