pub fn daemon(nochdir: bool, noclose: bool) -> Result<Fork>Expand description
The daemon function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons.
nochdir = false, changes the current working directory to the root (/).noclose = false, redirects stdin, stdout, and stderr to/dev/null
§Behavior Change in v0.4.0
Previously, noclose = false would close stdio file descriptors.
Now it redirects them to /dev/null instead, which is safer and prevents
file descriptor reuse bugs. This matches industry standard implementations
(libuv, systemd, BSD daemon(3)).
§Errors
Returns an io::Error if any of the underlying system calls fail:
- fork fails (e.g., resource limits)
- setsid fails (e.g., already a session leader)
- chdir fails (when
nochdiris false) - redirect_stdio fails (when
nocloseis false)
Example:
use fork::{daemon, Fork};
use std::process::Command;
if let Ok(Fork::Child) = daemon(false, false) {
Command::new("sleep")
.arg("3")
.output()
.expect("failed to execute process");
}