redirect_stdio

Function redirect_stdio 

Source
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:

  1. Opens /dev/null with O_RDWR
  2. Uses dup2() to redirect fds 0, 1, 2 to /dev/null
  3. 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/null cannot be opened
  • dup2() 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");