std/sys/pal/unix/
pipe.rs

1use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
2use crate::mem;
3use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
4use crate::sys::fd::FileDesc;
5use crate::sys::{cvt, cvt_r};
6use crate::sys_common::{FromInner, IntoInner};
7
8////////////////////////////////////////////////////////////////////////////////
9// Anonymous pipes
10////////////////////////////////////////////////////////////////////////////////
11
12#[derive(Debug)]
13pub struct AnonPipe(FileDesc);
14
15pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
16    let mut fds = [0; 2];
17
18    // The only known way right now to create atomically set the CLOEXEC flag is
19    // to use the `pipe2` syscall. This was added to Linux in 2.6.27, glibc 2.9
20    // and musl 0.9.3, and some other targets also have it.
21    cfg_select! {
22        any(
23            target_os = "dragonfly",
24            target_os = "freebsd",
25            target_os = "hurd",
26            target_os = "illumos",
27            target_os = "linux",
28            target_os = "netbsd",
29            target_os = "openbsd",
30            target_os = "cygwin",
31            target_os = "redox"
32        ) => {
33            unsafe {
34                cvt(libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC))?;
35                Ok((AnonPipe(FileDesc::from_raw_fd(fds[0])), AnonPipe(FileDesc::from_raw_fd(fds[1]))))
36            }
37        }
38        _ => {
39            unsafe {
40                cvt(libc::pipe(fds.as_mut_ptr()))?;
41
42                let fd0 = FileDesc::from_raw_fd(fds[0]);
43                let fd1 = FileDesc::from_raw_fd(fds[1]);
44                fd0.set_cloexec()?;
45                fd1.set_cloexec()?;
46                Ok((AnonPipe(fd0), AnonPipe(fd1)))
47            }
48        }
49    }
50}
51
52impl AnonPipe {
53    #[allow(dead_code)]
54    // FIXME: This function seems legitimately unused.
55    pub fn try_clone(&self) -> io::Result<Self> {
56        self.0.duplicate().map(Self)
57    }
58
59    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
60        self.0.read(buf)
61    }
62
63    pub fn read_buf(&self, buf: BorrowedCursor<'_>) -> io::Result<()> {
64        self.0.read_buf(buf)
65    }
66
67    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
68        self.0.read_vectored(bufs)
69    }
70
71    #[inline]
72    pub fn is_read_vectored(&self) -> bool {
73        self.0.is_read_vectored()
74    }
75
76    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
77        self.0.read_to_end(buf)
78    }
79
80    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
81        self.0.write(buf)
82    }
83
84    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
85        self.0.write_vectored(bufs)
86    }
87
88    #[inline]
89    pub fn is_write_vectored(&self) -> bool {
90        self.0.is_write_vectored()
91    }
92
93    #[allow(dead_code)]
94    // FIXME: This function seems legitimately unused.
95    pub fn as_file_desc(&self) -> &FileDesc {
96        &self.0
97    }
98}
99
100impl IntoInner<FileDesc> for AnonPipe {
101    fn into_inner(self) -> FileDesc {
102        self.0
103    }
104}
105
106pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
107    // Set both pipes into nonblocking mode as we're gonna be reading from both
108    // in the `select` loop below, and we wouldn't want one to block the other!
109    let p1 = p1.into_inner();
110    let p2 = p2.into_inner();
111    p1.set_nonblocking(true)?;
112    p2.set_nonblocking(true)?;
113
114    let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
115    fds[0].fd = p1.as_raw_fd();
116    fds[0].events = libc::POLLIN;
117    fds[1].fd = p2.as_raw_fd();
118    fds[1].events = libc::POLLIN;
119    loop {
120        // wait for either pipe to become readable using `poll`
121        cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?;
122
123        if fds[0].revents != 0 && read(&p1, v1)? {
124            p2.set_nonblocking(false)?;
125            return p2.read_to_end(v2).map(drop);
126        }
127        if fds[1].revents != 0 && read(&p2, v2)? {
128            p1.set_nonblocking(false)?;
129            return p1.read_to_end(v1).map(drop);
130        }
131    }
132
133    // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
134    // EAGAIN. If we hit EOF, then this will happen because the underlying
135    // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
136    // this case we flip the other fd back into blocking mode and read
137    // whatever's leftover on that file descriptor.
138    fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> {
139        match fd.read_to_end(dst) {
140            Ok(_) => Ok(true),
141            Err(e) => {
142                if e.raw_os_error() == Some(libc::EWOULDBLOCK)
143                    || e.raw_os_error() == Some(libc::EAGAIN)
144                {
145                    Ok(false)
146                } else {
147                    Err(e)
148                }
149            }
150        }
151    }
152}
153
154impl AsRawFd for AnonPipe {
155    #[inline]
156    fn as_raw_fd(&self) -> RawFd {
157        self.0.as_raw_fd()
158    }
159}
160
161impl AsFd for AnonPipe {
162    fn as_fd(&self) -> BorrowedFd<'_> {
163        self.0.as_fd()
164    }
165}
166
167impl IntoRawFd for AnonPipe {
168    fn into_raw_fd(self) -> RawFd {
169        self.0.into_raw_fd()
170    }
171}
172
173impl FromRawFd for AnonPipe {
174    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
175        Self(FromRawFd::from_raw_fd(raw_fd))
176    }
177}
178
179impl FromInner<FileDesc> for AnonPipe {
180    fn from_inner(fd: FileDesc) -> Self {
181        Self(fd)
182    }
183}