pipe in std::io - Rust (original) (raw)

Function pipe

1.87.0 · Source

pub fn pipe() -> Result<(PipeReader, PipeWriter)>

Expand description

Create an anonymous pipe.

§Behavior

A pipe is a one-way data channel provided by the OS, which works across processes. A pipe is typically used to communicate between two or more separate processes, as there are better, faster ways to communicate within a single process.

In particular:

§Platform-specific behavior

This function currently corresponds to the pipe function on Unix and theCreatePipe function on Windows.

Note that this may change in the future.

§Capacity

Pipe capacity is platform dependent. To quote the Linux man page:

Different implementations have different limits for the pipe capacity. Applications should not rely on a particular capacity: an application should be designed so that a reading process consumes data as soon as it is available, so that a writing process does not remain blocked.

§Examples

use std::process::Command;
use std::io::{pipe, Read, Write};
let (ping_rx, mut ping_tx) = pipe()?;
let (mut pong_rx, pong_tx) = pipe()?;

// Spawn a process that echoes its input.
let mut echo_server = Command::new("cat").stdin(ping_rx).stdout(pong_tx).spawn()?;

ping_tx.write_all(b"hello")?;
// Close to unblock echo_server's reader.
drop(ping_tx);

let mut buf = String::new();
// Block until echo_server's writer is closed.
pong_rx.read_to_string(&mut buf)?;
assert_eq!(&buf, "hello");

echo_server.wait()?;