pub fn dup2_stdout<Fd: AsFd>(fd: Fd) -> Result<()>
Expand description
Duplicate fd
with Stdout, i.e., Stdout redirection.
ยงExamples
Redirect the Stdout to file foo and restore it:
use nix::fcntl::open;
use nix::fcntl::OFlag;
use nix::sys::stat::Mode;
use nix::unistd::dup;
use nix::unistd::dup2_stdout;
use std::io::{stdout, Write};
let mut stdout = stdout();
// Save the previous Stdout so that we can restore it
let saved_stdout = dup(&stdout).unwrap();
let foo = open(
"foo",
OFlag::O_RDWR | OFlag::O_CLOEXEC | OFlag::O_CREAT | OFlag::O_EXCL,
Mode::S_IRWXU,
)
.unwrap();
// Now our Stdout has been redirected to file foo
dup2_stdout(foo).unwrap();
// Let's say hi to foo
// NOTE: add a newline here to flush the buffer
stdout.write(b"Hi, foo!\n").unwrap();
// Restore the Stdout
dup2_stdout(saved_stdout).unwrap();
// Let's say hi to Stdout
// NOTE: add a newline here to flush the buffer
stdout.write(b"Hi, Stdout!\n").unwrap();