Crate io_redirect

Crate io_redirect 

Source
Expand description

Cross-platform I/O redirection.

This crate provides a Redirectable<T> trait, platform-specific implementations of this trait, and convenience methods for handling stdout and stderr redirection. This is most useful if you can’t print to stdout or stderr directly (e.g., a systemd generator) or need to hijack file access without changing user code.

§Platform Support

PlatformRequired FeaturesFile to FileStdout/Stderr to FileAny FD to Any FD
Unix-likelibc_on_unixYesYesYes
Windowswindows-sysNoYesNo
Windowslibc_on_windowsYesNoNo

All features are enabled by default on all platforms.

On Windows, `Redirectable` trait accepts any `T` that can be converted into a handle. Be careful not to feed handles without file semantics such as a thread handle. Also, if the handle is being directly used elsewhere, it won't benefit from redirection.

§Usage

For a more detailed example, see the selftest executable.

§File to File

use io_redirect::Redirectable;

let mut file_src = File::create("src.txt").unwrap();
let file_dst = File::create("dst.txt").unwrap();

file_src.redirect(&file_dst).unwrap();

§Redirect Standard Streams to a File

use io_redirect::redirect_std_to_path;

let some_path = PathBuf::from("/dev/kmsg");

// redirect both stdout and stderr to the same file
redirect_std_to_path(some_path.as_path(), true).unwrap();

// or just one stream
stdout().redirect(some_path.as_path()).unwrap();

§Notes and Caveats

  • Resource Management: Avoid using Redirectable<Path>::redirect(...) multiple times on the same entity as each call will leak a file descriptor. Redirectable<File> does not suffer from the same.
  • OS-Specific Behavior: Not all features may function identically across platforms; ensure feature flags match the intended target for compilation.

Traits§

Descriptable
Redirectable
A trait to represent entities that can have their I/O redirected to a specified target.

Functions§

redirect_std_to_path

Type Aliases§

Descriptor