Trait StdioExt

trait StdioExt: crate::sealed::Sealed

Required Methods

fn set_fd<T: Into<OwnedFd>>(self: &mut Self, fd: T) -> io::Result<()>

Redirects the stdio file descriptor to point to the file description underpinning fd.

Rust std::io write buffers (if any) are flushed, but other runtimes (e.g. C stdio) or libraries that acquire a clone of the file descriptor will not be aware of this change.

Platform-specific behavior

This is currently implemented using

  • fd_renumber on wasip1
  • dup2 on most unixes
#![feature(stdio_swap)]
use std::io::{self, Read, Write};
use std::os::unix::io::StdioExt;

fn main() -> io::Result<()> {
   let (reader, mut writer) = io::pipe()?;
   let mut stdin = io::stdin();
   stdin.set_fd(reader)?;
   writer.write_all(b"Hello, world!")?;
   let mut buffer = vec![0; 13];
   assert_eq!(stdin.read(&mut buffer)?, 13);
   assert_eq!(&buffer, b"Hello, world!");
   Ok(())
}
fn replace_fd<T: Into<OwnedFd>>(self: &mut Self, replace_with: T) -> io::Result<OwnedFd>

Redirects the stdio file descriptor and returns a new OwnedFd backed by the previous file description.

See set_fd() for details.

fn take_fd(self: &mut Self) -> io::Result<OwnedFd>

Redirects the stdio file descriptor to the null device (/dev/null) and returns a new OwnedFd backed by the previous file description.

Programs that communicate structured data via stdio can use this early in main() to extract the fds, treat them as other IO types (File, UnixStream, etc), apply custom buffering or avoid interference from stdio use later in the program.

See set_fd() for additional details.

Implementors