Skip to content

Commit 3f11cdd

Browse files
Stdout/stderr merging example
1 parent 37c317d commit 3f11cdd

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

content/Rust-1.87.0.md

+16-17
Original file line numberDiff line numberDiff line change
@@ -28,30 +28,29 @@ If you'd like to help us out by testing future releases, you might consider upda
2828
### Anonymous pipes
2929

3030
1.87 adds access to anonymous pipes to the standard library. This includes
31-
integration with `std::process::Command`'s input/output methods.
32-
33-
As a toy example, this program uses pipes to stream data into `cat` and read the output:
31+
integration with `std::process::Command`'s input/output methods. For example,
32+
joining the stdout and stderr streams into one is now relatively
33+
straightforward, as shown below, while it used to require either extra threads
34+
or platform-specific functions.
3435

3536
```rust
3637
use std::process::Command;
37-
use std::io::{pipe, Read, Write};
38-
39-
let (ping_rx, mut ping_tx) = pipe()?;
40-
let (mut pong_rx, pong_tx) = pipe()?;
38+
use std::io::Read;
4139

42-
// Spawn a process that echoes its input.
43-
let mut echo_server = Command::new("cat").stdin(ping_rx).stdout(pong_tx).spawn()?;
40+
let (mut recv, send) = std::io::pipe()?;
4441

45-
ping_tx.write_all(b"hello")?;
46-
// Close to unblock echo_server's reader.
47-
drop(ping_tx);
42+
let mut command = Command::new("path/to/bin")
43+
// Both stdout and stderr will write to the same pipe, combining the two.
44+
.stdout(send.try_clone()?)
45+
.stderr(send)
46+
.spawn()?;
4847

49-
let mut buf = String::new();
50-
// Block until echo_server's writer is closed.
51-
pong_rx.read_to_string(&mut buf)?;
52-
assert_eq!(&buf, "hello");
48+
let mut output = Vec::new();
49+
recv.read_to_end(&mut output)?;
5350

54-
echo_server.wait()?;
51+
// It's important that we read from the pipe before the process exits, to avoid
52+
// filling the OS buffers if the program emits too much output.
53+
assert!(command.wait()?.success());
5554
```
5655

5756
### Safe architecture intrinsics

0 commit comments

Comments
 (0)