[go: up one dir, main page]

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/// # #[cfg(miri)] fn main() {}
44/// # #[cfg(not(miri))]
45/// # fn main() -> std::io::Result<()> {
46/// use std::io::{Read, Write, pipe};
47/// use std::process::Command;
48/// let (ping_reader, mut ping_writer) = pipe()?;
49/// let (mut pong_reader, pong_writer) = pipe()?;
50///
51/// // Spawn a child process that echoes its input.
52/// let mut echo_command = Command::new("cat");
53/// echo_command.stdin(ping_reader);
54/// echo_command.stdout(pong_writer);
55/// let mut echo_child = echo_command.spawn()?;
56///
57/// // Send input to the child process. Note that because we're writing all the input before we
58/// // read any output, this could deadlock if the child's input and output pipe buffers both
59/// // filled up. Those buffers are usually at least a few KB, so "hello" is fine, but for longer
60/// // inputs we'd need to read and write at the same time, e.g. using threads.
61/// ping_writer.write_all(b"hello")?;
62///
63/// // `cat` exits when it reads EOF from stdin, but that can't happen while any ping writer
64/// // remains open. We need to drop our ping writer, or read_to_string will deadlock below.
65/// drop(ping_writer);
66///
67/// // The pong reader can't report EOF while any pong writer remains open. Our Command object is
68/// // holding a pong writer, and again read_to_string will deadlock if we don't drop it.
69/// drop(echo_command);
70///
71/// let mut buf = String::new();
72/// // Block until `cat` closes its stdout (a pong writer).
73/// pong_reader.read_to_string(&mut buf)?;
74/// assert_eq!(&buf, "hello");
75///
76/// // At this point we know `cat` has exited, but we still need to wait to clean up the "zombie".
77/// echo_child.wait()?;
78/// # Ok(())
79/// # }
80/// ```
81/// [changes]: io#platform-specific-behavior
82/// [man page]: https://man7.org/linux/man-pages/man7/pipe.7.html
83#[stable(feature = "anonymous_pipe", since = "1.87.0")]
84#[inline]
85pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> {
86    imp::pipe().map(|(reader, writer)| (PipeReader(reader), PipeWriter(writer)))
87}
88
89/// Read end of an anonymous pipe.
90#[stable(feature = "anonymous_pipe", since = "1.87.0")]
91#[derive(Debug)]
92pub struct PipeReader(pub(crate) imp::Pipe);
93
94/// Write end of an anonymous pipe.
95#[stable(feature = "anonymous_pipe", since = "1.87.0")]
96#[derive(Debug)]
97pub struct PipeWriter(pub(crate) imp::Pipe);
98
99impl FromInner<imp::Pipe> for PipeReader {
100    fn from_inner(inner: imp::Pipe) -> Self {
101        Self(inner)
102    }
103}
104
105impl IntoInner<imp::Pipe> for PipeReader {
106    fn into_inner(self) -> imp::Pipe {
107        self.0
108    }
109}
110
111impl FromInner<imp::Pipe> for PipeWriter {
112    fn from_inner(inner: imp::Pipe) -> Self {
113        Self(inner)
114    }
115}
116
117impl IntoInner<imp::Pipe> for PipeWriter {
118    fn into_inner(self) -> imp::Pipe {
119        self.0
120    }
121}
122
123impl PipeReader {
124    /// Creates a new [`PipeReader`] instance that shares the same underlying file description.
125    ///
126    /// # Examples
127    ///
128    /// ```no_run
129    /// # #[cfg(miri)] fn main() {}
130    /// # #[cfg(not(miri))]
131    /// # fn main() -> std::io::Result<()> {
132    /// use std::fs;
133    /// use std::io::{pipe, Write};
134    /// use std::process::Command;
135    /// const NUM_SLOT: u8 = 2;
136    /// const NUM_PROC: u8 = 5;
137    /// const OUTPUT: &str = "work.txt";
138    ///
139    /// let mut jobs = vec![];
140    /// let (reader, mut writer) = pipe()?;
141    ///
142    /// // Write NUM_SLOT characters the pipe.
143    /// writer.write_all(&[b'|'; NUM_SLOT as usize])?;
144    ///
145    /// // Spawn several processes that read a character from the pipe, do some work, then
146    /// // write back to the pipe. When the pipe is empty, the processes block, so only
147    /// // NUM_SLOT processes can be working at any given time.
148    /// for _ in 0..NUM_PROC {
149    ///     jobs.push(
150    ///         Command::new("bash")
151    ///             .args(["-c",
152    ///                 &format!(
153    ///                      "read -n 1\n\
154    ///                       echo -n 'x' >> '{OUTPUT}'\n\
155    ///                       echo -n '|'",
156    ///                 ),
157    ///             ])
158    ///             .stdin(reader.try_clone()?)
159    ///             .stdout(writer.try_clone()?)
160    ///             .spawn()?,
161    ///     );
162    /// }
163    ///
164    /// // Wait for all jobs to finish.
165    /// for mut job in jobs {
166    ///     job.wait()?;
167    /// }
168    ///
169    /// // Check our work and clean up.
170    /// let xs = fs::read_to_string(OUTPUT)?;
171    /// fs::remove_file(OUTPUT)?;
172    /// assert_eq!(xs, "x".repeat(NUM_PROC.into()));
173    /// # Ok(())
174    /// # }
175    /// ```
176    #[stable(feature = "anonymous_pipe", since = "1.87.0")]
177    pub fn try_clone(&self) -> io::Result<Self> {
178        self.0.try_clone().map(Self)
179    }
180}
181
182impl PipeWriter {
183    /// Creates a new [`PipeWriter`] instance that shares the same underlying file description.
184    ///
185    /// # Examples
186    ///
187    /// ```no_run
188    /// # #[cfg(miri)] fn main() {}
189    /// # #[cfg(not(miri))]
190    /// # fn main() -> std::io::Result<()> {
191    /// use std::process::Command;
192    /// use std::io::{pipe, Read};
193    /// let (mut reader, writer) = pipe()?;
194    ///
195    /// // Spawn a process that writes to stdout and stderr.
196    /// let mut peer = Command::new("bash")
197    ///     .args([
198    ///         "-c",
199    ///         "echo -n foo\n\
200    ///          echo -n bar >&2"
201    ///     ])
202    ///     .stdout(writer.try_clone()?)
203    ///     .stderr(writer)
204    ///     .spawn()?;
205    ///
206    /// // Read and check the result.
207    /// let mut msg = String::new();
208    /// reader.read_to_string(&mut msg)?;
209    /// assert_eq!(&msg, "foobar");
210    ///
211    /// peer.wait()?;
212    /// # Ok(())
213    /// # }
214    /// ```
215    #[stable(feature = "anonymous_pipe", since = "1.87.0")]
216    pub fn try_clone(&self) -> io::Result<Self> {
217        self.0.try_clone().map(Self)
218    }
219}
220
221#[stable(feature = "anonymous_pipe", since = "1.87.0")]
222impl io::Read for &PipeReader {
223    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
224        self.0.read(buf)
225    }
226    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
227        self.0.read_vectored(bufs)
228    }
229    #[inline]
230    fn is_read_vectored(&self) -> bool {
231        self.0.is_read_vectored()
232    }
233    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
234        self.0.read_to_end(buf)
235    }
236    fn read_buf(&mut self, buf: io::BorrowedCursor<'_>) -> io::Result<()> {
237        self.0.read_buf(buf)
238    }
239}
240
241#[stable(feature = "anonymous_pipe", since = "1.87.0")]
242impl io::Read for PipeReader {
243    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
244        self.0.read(buf)
245    }
246    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
247        self.0.read_vectored(bufs)
248    }
249    #[inline]
250    fn is_read_vectored(&self) -> bool {
251        self.0.is_read_vectored()
252    }
253    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
254        self.0.read_to_end(buf)
255    }
256    fn read_buf(&mut self, buf: io::BorrowedCursor<'_>) -> io::Result<()> {
257        self.0.read_buf(buf)
258    }
259}
260
261#[stable(feature = "anonymous_pipe", since = "1.87.0")]
262impl io::Write for &PipeWriter {
263    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
264        self.0.write(buf)
265    }
266    #[inline]
267    fn flush(&mut self) -> io::Result<()> {
268        Ok(())
269    }
270    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
271        self.0.write_vectored(bufs)
272    }
273    #[inline]
274    fn is_write_vectored(&self) -> bool {
275        self.0.is_write_vectored()
276    }
277}
278
279#[stable(feature = "anonymous_pipe", since = "1.87.0")]
280impl io::Write for PipeWriter {
281    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
282        self.0.write(buf)
283    }
284    #[inline]
285    fn flush(&mut self) -> io::Result<()> {
286        Ok(())
287    }
288    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
289        self.0.write_vectored(bufs)
290    }
291    #[inline]
292    fn is_write_vectored(&self) -> bool {
293        self.0.is_write_vectored()
294    }
295}