pub fn daemonize<T: Into<PathBuf>>(pid_file: T) -> Result<impl AsHandle, Error>Expand description
this will fork the calling process twice and return a handle to the grandchild process aka daemon, use the handle to detach from the parent process
before Handle::detach is called the daemon process has it’s STDOUT/STDERR
piped to the parent process’ STDOUT/STDERR, this way any errors encountered by the
daemon during start up is reported.
Examples found in repository?
examples/simple.rs (line 6)
5fn main() {
6 match daemonize("pid_file") {
7 // we are now in the daemon, use this handle to detach from the parent process
8 Ok(mut handle) => {
9 let mut count = 0;
10 loop {
11 // the daemon's output is piped to the parent process' stdout
12 println!("Count: {}", count);
13 if count == 5 {
14 handle.detach_with_msg("count has reached 5, continuing in background");
15 }
16 thread::sleep(time::Duration::from_secs(1));
17 count += 1;
18 }
19 }
20 // the daemon or the parent process may receive this error,
21 // just print it and exit
22 Err(e) => {
23 // if this is the daemon, this is piped to the parent's stderr
24 eprintln!("{}", e);
25 // don't forget to flush
26 let _ = io::stderr().flush();
27 process::exit(1);
28 }
29 }
30}