[][src]Crate spirit_daemonize

A spirit helpers and configuration fragments for daemonization.

The helpers in here extend the spirit configuration framework to automatically go into background based on user's configuration and command line options.

Examples

extern crate spirit;
extern crate spirit_daemonize;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate structopt;

use spirit::Spirit;
use spirit_daemonize::{Daemon, Opts as DaemonOpts};

// From config files
#[derive(Default, Deserialize)]
struct Cfg {
    #[serde(default)]
    daemon: Daemon,
}

impl Cfg {
   fn daemon(&self) -> Daemon {
       self.daemon.clone()
   }
}

// From command line
#[derive(Debug, StructOpt)]
struct Opts {
    #[structopt(flatten)]
    daemon: DaemonOpts,
}

impl Opts {
   fn daemon(&self) -> &DaemonOpts {
       &self.daemon
   }
}

fn main() {
     Spirit::<Opts, Cfg>::new()
        .config_helper(Cfg::daemon, spirit_daemonize::with_opts(Opts::daemon), "daemonize")
        .run(|_spirit| {
            // Possibly daemonized program goes here
            Ok(())
        });
}

Added options

The program above gets the -d command line option, which enables daemonization. Furthermore, the configuration now understands a new daemon section, with these options:

  • user: The user to become. Either a numeric ID or name. If not present, it doesn't change the user.
  • group: Similar as user, but with group.
  • pid-file: A pid file to write on startup. If not present, nothing is stored.
  • workdir: A working directory it'll switch into. If not set, defaults to /.
  • daemonize: Should this go into background or not? If combined with the Opts, it can be overridden on command line.

Multithreaded applications

As daemonization is done by using fork, you should start any threads after you initialize the spirit. Otherwise you'll lose the threads (and further bad things will happen).

The daemonization happens inside the config_validator callback. If other config validators need to start any threads, they should be plugged in after the daemonization callback. However, the safer option is to start them inside the run method.

Structs

Daemon

A configuration fragment for configuration of daemonization.

Opts

Command line options fragment.

UserDaemon

A stripped-down version of Daemon without the user-switching options.

Enums

SecId

Configuration of either user or a group.

Functions

with_opts

Wraps an extractor of an Opts struct to form a transformation closure for Daemon config helper.