Function pipe

Source
pub fn pipe() -> Result<(PipeReader, PipeWriter), Error>
🔬This is a nightly-only experimental API. (anonymous_pipe)
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:

  • A read on a PipeReader blocks until the pipe is non-empty.
  • A write on a PipeWriter blocks when the pipe is full.
  • When all copies of a PipeWriter are closed, a read on the corresponding PipeReader returns EOF.
  • PipeWriter can be shared, and multiple processes or threads can write to it at once, but writes (above a target-specific threshold) may have their data interleaved.
  • PipeReader can be shared, and multiple processes or threads can read it at once. Any given byte will only get consumed by one reader. There are no guarantees about data interleaving.
  • Portable applications cannot assume any atomicity of messages larger than a single byte.

§Platform-specific behavior

This function currently corresponds to the pipe function on Unix and the CreatePipe 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

#![feature(anonymous_pipe)]
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()?;