pub fn redirect_stdio() -> Result<()>Expand description
Redirect stdin, stdout, stderr to /dev/null
This is the recommended way to detach from the controlling terminal
in daemon processes. Unlike close_fd(), this keeps file descriptors
0, 1, 2 occupied (pointing to /dev/null), preventing them from being
reused by subsequent open() calls.
This prevents bugs where println!, eprintln!, or panic output
accidentally writes to data files that happened to get assigned fd 0, 1, or 2.
§Implementation
This function:
- Opens
/dev/nullwithO_RDWR - Uses
dup2()to redirect fds 0, 1, 2 to/dev/null - Closes the extra file descriptor if it was > 2
This is the same approach used by libuv, systemd, and BSD daemon(3).
§Errors
Returns an io::Error if:
/dev/nullcannot be openeddup2()fails to redirect any of the file descriptors
§Example
use fork::redirect_stdio;
use std::fs::File;
redirect_stdio()?;
// Now safe: files will get fd >= 3
let log = File::create("app.log")?;
// This goes to /dev/null (safely discarded), not to app.log
println!("debug message");