MCPcopy Create free account
hub / github.com/bytecodealliance/rustix / main

Function main

examples/dup2_to_replace_stdio.rs:5–38  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

3
4#[cfg(all(not(windows), feature = "pipe", feature = "stdio"))]
5fn main() -> std::io::Result<()> {
6 use rustix::pipe::pipe;
7 use rustix::stdio::{dup2_stdin, dup2_stdout};
8
9 // Create some new file descriptors that we'll use to replace stdio's file
10 // descriptors with.
11 let (reader, writer) = pipe()?;
12
13 // Use `dup2` to copy our new file descriptors over the stdio file
14 // descriptors.
15 //
16 // Rustix has a plain `dup2` function too, but it requires a
17 // `&mut OwnedFd`, so these helper functions make it easier to use when
18 // replacing stdio fds.
19 dup2_stdin(&reader)?;
20 dup2_stdout(&writer)?;
21
22 // We can also drop the original file descriptors now, since `dup2` creates
23 // new file descriptors with independent lifetimes.
24 drop(reader);
25 drop(writer);
26
27 // Now we can print to “stdout” in the usual way, and it'll go to our pipe.
28 println!("hello, world!");
29
30 // And we can read from stdin, and it'll read from our pipe. It's a little
31 // silly that we connected our stdout to our own stdin, but it's just an
32 // example 😀.
33 let mut s = String::new();
34 std::io::stdin().read_line(&mut s)?;
35 assert_eq!(s, "hello, world!\n");
36
37 Ok(())
38}
39
40#[cfg(not(all(not(windows), feature = "pipe", feature = "stdio")))]
41fn main() -> Result<(), &'static str> {

Callers

nothing calls this directly

Calls 4

dup2_stdinFunction · 0.85
dup2_stdoutFunction · 0.85
stdinFunction · 0.85
pipeFunction · 0.50

Tested by

no test coverage detected