conch_runtime_pshaw/io/
pipe.rs

1use crate::io::FileDesc;
2use crate::sys;
3use crate::IntoInner;
4use std::io::Result as IoResult;
5
6/// A wrapper for a reader and writer OS pipe pair.
7#[derive(Debug)]
8pub struct Pipe {
9    /// The reader end of the pipe. Anything written to the writer end can be read here.
10    pub reader: FileDesc,
11    /// The writer end of the pipe. Anything written here can be read from the reader end.
12    pub writer: FileDesc,
13}
14
15impl Pipe {
16    /// Creates and returns a new pipe pair.
17    /// On Unix systems, both file descriptors of the pipe will have their CLOEXEC flags set,
18    /// however, note that the setting of the flags is nonatomic on BSD systems.
19    pub fn new() -> IoResult<Pipe> {
20        let (reader, writer) = sys::io::pipe()?;
21        Ok(Pipe {
22            reader: FileDesc::from_inner(reader),
23            writer: FileDesc::from_inner(writer),
24        })
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::Pipe;
31    use std::io::{Read, Write};
32    use std::thread;
33
34    #[test]
35    fn smoke() {
36        let msg = "pipe message";
37        let Pipe {
38            mut reader,
39            mut writer,
40        } = Pipe::new().unwrap();
41
42        let guard = thread::spawn(move || {
43            writer.write_all(msg.as_bytes()).unwrap();
44            writer.flush().unwrap();
45            drop(writer);
46        });
47
48        let mut read = String::new();
49        reader.read_to_string(&mut read).unwrap();
50        guard.join().unwrap();
51        assert_eq!(msg, read);
52    }
53}