parity_daemonize/
lib.rs

1// Copyright 2015-2018 Parity Technologies (UK) Ltd.
2// This file is part of Parity.
3
4// Parity is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Parity is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Parity.  If not, see <http://www.gnu.org/licenses/>.
16
17use crate::error::{Error, ErrorKind};
18use std::path::PathBuf;
19
20pub mod error;
21
22mod platform;
23
24type Result<T> = std::result::Result<T, Error>;
25
26/// Handle returned from `daemonize` to the daemon process
27/// the daemon should use this handle to detach itself from the
28/// parent process, In cases where your program needs to run set up before starting
29/// this can be useful, as the daemon will pipe it's stdout/stderr to the parent process
30/// to communicate if start up was successful
31pub trait AsHandle {
32	type Fd;
33
34	/// Creates a `Handle` from a raw file descriptor
35	fn from_fd(fd: Self::Fd) -> Self;
36
37	/// Detach the daemon from the parent process
38	/// this will write "Daemon started successfully" to stdout
39	/// before detaching
40	///
41	/// # panics
42	/// if detach is called more than once
43	fn detach(&mut self);
44
45	/// Detach the daemon from the parent process
46	/// with a custom message to be printed to stdout before detaching
47	///
48	/// # panics
49	/// if detach_with_msg is called more than once
50	fn detach_with_msg<T: AsRef<[u8]>>(&mut self, msg: T);
51}
52
53#[macro_export]
54macro_rules! map_err {
55	($e:expr, $err:expr) => {
56		match $e {
57			-1 => {
58				Err::<_, crate::error::Error>(From::from($err))
59			}
60			other => Ok(other),
61		}
62	};
63}
64
65/// this will fork the calling process twice and return a handle to the
66/// grandchild process aka daemon, use the handle to detach from the parent process
67///
68/// before `Handle::detach` is called the daemon process has it's STDOUT/STDERR
69/// piped to the parent process' STDOUT/STDERR, this way any errors encountered by the
70/// daemon during start up is reported.
71pub fn daemonize<T: Into<PathBuf>>(pid_file: T) -> Result<impl AsHandle> {
72	platform::daemonize(pid_file)
73}