Skip to main content

std/io/
pipe.rs

1use crate::io;
2use crate::sys::{FromInner, IntoInner, pipe as imp};
3
4/// Creates an anonymous pipe.
5///
6/// # Behavior
7///
8/// A pipe is a one-way data channel provided by the OS, which works across processes. A pipe is
9/// typically used to communicate between two or more separate processes, as there are better,
10/// faster ways to communicate within a single process.
11///
12/// In particular:
13///
14/// * A read on a [`PipeReader`] blocks until the pipe is non-empty.
15/// * A write on a [`PipeWriter`] blocks when the pipe is full.
16/// * When all copies of a [`PipeWriter`] are closed, a read on the corresponding [`PipeReader`]
17///   returns EOF.
18/// * [`PipeWriter`] can be shared, and multiple processes or threads can write to it at once, but
19///   writes (above a target-specific threshold) may have their data interleaved.
20/// * [`PipeReader`] can be shared, and multiple processes or threads can read it at once. Any
21///   given byte will only get consumed by one reader. There are no guarantees about data
22///   interleaving.
23/// * Portable applications cannot assume any atomicity of messages larger than a single byte.
24///
25/// # Platform-specific behavior
26///
27/// This function currently corresponds to the `pipe` function on Unix and the
28/// `CreatePipe` function on Windows.
29///
30/// Note that this [may change in the future][changes].
31///
32/// # Capacity
33///
34/// Pipe capacity is platform dependent. To quote the Linux [man page]:
35///
36/// > Different implementations have different limits for the pipe capacity. Applications should
37/// > not rely on a particular capacity: an application should be designed so that a reading process
38/// > consumes data as soon as it is available, so that a writing process does not remain blocked.
39///
40/// # Example
41///
42/// ```no_run
43/// # fn main() -> std::io::Result<()> {
44/// use std::io::{Read, Write, pipe};
45/// use std::process::Command;
46/// let (ping_reader, mut ping_writer) = pipe()?;
47/// let (mut pong_reader, pong_writer) = pipe()?;
48///
49/// // Spawn a child process that echoes its input.
50/// let mut echo_command = Command::new("cat");
51/// echo_command.stdin(ping_reader);
52/// echo_command.stdout(pong_writer);
53/// let mut echo_child = echo_command.spawn()?;
54///
55/// // Send input to the child process. Note that because we're writing all the input before we
56/// // read any output, this could deadlock if the child's input and output pipe buffers both
57/// // filled up. Those buffers are usually at least a few KB, so "hello" is fine, but for longer
58/// // inputs we'd need to read and write at the same time, e.g. using threads.
59/// ping_writer.write_all(b"hello")?;
60///
61/// // `cat` exits when it reads EOF from stdin, but that can't happen while any ping writer
62/// // remains open. We need to drop our ping writer, or read_to_string will deadlock below.
63/// drop(ping_writer);
64///
65/// // The pong reader can't report EOF while any pong writer remains open. Our Command object is
66/// // holding a pong writer, and again read_to_string will deadlock if we don't drop it.
67/// drop(echo_command);
68///
69/// let mut buf = String::new();
70/// // Block until `cat` closes its stdout (a pong writer).
71/// pong_reader.read_to_string(&mut buf)?;
72/// assert_eq!(&buf, "hello");
73///
74/// // At this point we know `cat` has exited, but we still need to wait to clean up the "zombie".
75/// echo_child.wait()?;
76/// # Ok(())
77/// # }
78/// ```
79/// [changes]: io#platform-specific-behavior
80/// [man page]: https://man7.org/linux/man-pages/man7/pipe.7.html
81#[stable(feature = "anonymous_pipe", since = "1.87.0")]
82#[inline]
83pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> {
84    imp::pipe().map(|(reader, writer)| (PipeReader(reader), PipeWriter(writer)))
85}
86
87/// Read end of an anonymous pipe.
88#[stable(feature = "anonymous_pipe", since = "1.87.0")]
89#[derive(Debug)]
90pub struct PipeReader(pub(crate) imp::Pipe);
91
92/// Write end of an anonymous pipe.
93#[stable(feature = "anonymous_pipe", since = "1.87.0")]
94#[derive(Debug)]
95pub struct PipeWriter(pub(crate) imp::Pipe);
96
97impl FromInner<imp::Pipe> for PipeReader {
98    fn from_inner(inner: imp::Pipe) -> Self {
99        Self(inner)
100    }
101}
102
103impl IntoInner<imp::Pipe> for PipeReader {
104    fn into_inner(self) -> imp::Pipe {
105        self.0
106    }
107}
108
109impl FromInner<imp::Pipe> for PipeWriter {
110    fn from_inner(inner: imp::Pipe) -> Self {
111        Self(inner)
112    }
113}
114
115impl IntoInner<imp::Pipe> for PipeWriter {
116    fn into_inner(self) -> imp::Pipe {
117        self.0
118    }
119}
120
121impl PipeReader {
122    /// Creates a new [`PipeReader`] instance that shares the same underlying file description.
123    ///
124    /// # Examples
125    ///
126    /// ```no_run
127    /// # fn main() -> std::io::Result<()> {
128    /// use std::fs;
129    /// use std::io::{pipe, Write};
130    /// use std::process::Command;
131    /// const NUM_SLOT: u8 = 2;
132    /// const NUM_PROC: u8 = 5;
133    /// const OUTPUT: &str = "work.txt";
134    ///
135    /// let mut jobs = vec![];
136    /// let (reader, mut writer) = pipe()?;
137    ///
138    /// // Write NUM_SLOT characters the pipe.
139    /// writer.write_all(&[b'|'; NUM_SLOT as usize])?;
140    ///
141    /// // Spawn several processes that read a character from the pipe, do some work, then
142    /// // write back to the pipe. When the pipe is empty, the processes block, so only
143    /// // NUM_SLOT processes can be working at any given time.
144    /// for _ in 0..NUM_PROC {
145    ///     jobs.push(
146    ///         Command::new("bash")
147    ///             .args(["-c",
148    ///                 &format!(
149    ///                      "read -n 1\n\
150    ///                       echo -n 'x' >> '{OUTPUT}'\n\
151    ///                       echo -n '|'",
152    ///                 ),
153    ///             ])
154    ///             .stdin(reader.try_clone()?)
155    ///             .stdout(writer.try_clone()?)
156    ///             .spawn()?,
157    ///     );
158    /// }
159    ///
160    /// // Wait for all jobs to finish.
161    /// for mut job in jobs {
162    ///     job.wait()?;
163    /// }
164    ///
165    /// // Check our work and clean up.
166    /// let xs = fs::read_to_string(OUTPUT)?;
167    /// fs::remove_file(OUTPUT)?;
168    /// assert_eq!(xs, "x".repeat(NUM_PROC.into()));
169    /// # Ok(())
170    /// # }
171    /// ```
172    #[stable(feature = "anonymous_pipe", since = "1.87.0")]
173    pub fn try_clone(&self) -> io::Result<Self> {
174        self.0.try_clone().map(Self)
175    }
176}
177
178impl PipeWriter {
179    /// Creates a new [`PipeWriter`] instance that shares the same underlying file description.
180    ///
181    /// # Examples
182    ///
183    /// ```no_run
184    /// # fn main() -> std::io::Result<()> {
185    /// use std::process::Command;
186    /// use std::io::{pipe, Read};
187    /// let (mut reader, writer) = pipe()?;
188    ///
189    /// // Spawn a process that writes to stdout and stderr.
190    /// let mut peer = Command::new("bash")
191    ///     .args([
192    ///         "-c",
193    ///         "echo -n foo\n\
194    ///          echo -n bar >&2"
195    ///     ])
196    ///     .stdout(writer.try_clone()?)
197    ///     .stderr(writer)
198    ///     .spawn()?;
199    ///
200    /// // Read and check the result.
201    /// let mut msg = String::new();
202    /// reader.read_to_string(&mut msg)?;
203    /// assert_eq!(&msg, "foobar");
204    ///
205    /// peer.wait()?;
206    /// # Ok(())
207    /// # }
208    /// ```
209    #[stable(feature = "anonymous_pipe", since = "1.87.0")]
210    pub fn try_clone(&self) -> io::Result<Self> {
211        self.0.try_clone().map(Self)
212    }
213}
214
215#[stable(feature = "anonymous_pipe", since = "1.87.0")]
216impl io::Read for &PipeReader {
217    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
218        self.0.read(buf)
219    }
220    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
221        self.0.read_vectored(bufs)
222    }
223    #[inline]
224    fn is_read_vectored(&self) -> bool {
225        self.0.is_read_vectored()
226    }
227    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
228        self.0.read_to_end(buf)
229    }
230    fn read_buf(&mut self, buf: io::BorrowedCursor<'_>) -> io::Result<()> {
231        self.0.read_buf(buf)
232    }
233}
234
235#[stable(feature = "anonymous_pipe", since = "1.87.0")]
236impl io::Read for PipeReader {
237    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
238        self.0.read(buf)
239    }
240    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
241        self.0.read_vectored(bufs)
242    }
243    #[inline]
244    fn is_read_vectored(&self) -> bool {
245        self.0.is_read_vectored()
246    }
247    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
248        self.0.read_to_end(buf)
249    }
250    fn read_buf(&mut self, buf: io::BorrowedCursor<'_>) -> io::Result<()> {
251        self.0.read_buf(buf)
252    }
253}
254
255#[stable(feature = "anonymous_pipe", since = "1.87.0")]
256impl io::Write for &PipeWriter {
257    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
258        self.0.write(buf)
259    }
260    #[inline]
261    fn flush(&mut self) -> io::Result<()> {
262        Ok(())
263    }
264    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
265        self.0.write_vectored(bufs)
266    }
267    #[inline]
268    fn is_write_vectored(&self) -> bool {
269        self.0.is_write_vectored()
270    }
271}
272
273#[stable(feature = "anonymous_pipe", since = "1.87.0")]
274impl io::Write for PipeWriter {
275    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
276        self.0.write(buf)
277    }
278    #[inline]
279    fn flush(&mut self) -> io::Result<()> {
280        Ok(())
281    }
282    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
283        self.0.write_vectored(bufs)
284    }
285    #[inline]
286    fn is_write_vectored(&self) -> bool {
287        self.0.is_write_vectored()
288    }
289}