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_if::cfg_if! {
22        if #[cfg(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        } else {
38            unsafe {
39                cvt(libc::pipe(fds.as_mut_ptr()))?;
40
41                let fd0 = FileDesc::from_raw_fd(fds[0]);
42                let fd1 = FileDesc::from_raw_fd(fds[1]);
43                fd0.set_cloexec()?;
44                fd1.set_cloexec()?;
45                Ok((AnonPipe(fd0), AnonPipe(fd1)))
46            }
47        }
48    }
49}
50
51impl AnonPipe {
52    #[allow(dead_code)]
53    // FIXME: This function seems legitimately unused.
54    pub fn try_clone(&self) -> io::Result<Self> {
55        self.0.duplicate().map(Self)
56    }
57
58    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
59        self.0.read(buf)
60    }
61
62    pub fn read_buf(&self, buf: BorrowedCursor<'_>) -> io::Result<()> {
63        self.0.read_buf(buf)
64    }
65
66    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
67        self.0.read_vectored(bufs)
68    }
69
70    #[inline]
71    pub fn is_read_vectored(&self) -> bool {
72        self.0.is_read_vectored()
73    }
74
75    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
76        self.0.read_to_end(buf)
77    }
78
79    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
80        self.0.write(buf)
81    }
82
83    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
84        self.0.write_vectored(bufs)
85    }
86
87    #[inline]
88    pub fn is_write_vectored(&self) -> bool {
89        self.0.is_write_vectored()
90    }
91
92    #[allow(dead_code)]
93    // FIXME: This function seems legitimately unused.
94    pub fn as_file_desc(&self) -> &FileDesc {
95        &self.0
96    }
97}
98
99impl IntoInner<FileDesc> for AnonPipe {
100    fn into_inner(self) -> FileDesc {
101        self.0
102    }
103}
104
105pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
106    // Set both pipes into nonblocking mode as we're gonna be reading from both
107    // in the `select` loop below, and we wouldn't want one to block the other!
108    let p1 = p1.into_inner();
109    let p2 = p2.into_inner();
110    p1.set_nonblocking(true)?;
111    p2.set_nonblocking(true)?;
112
113    let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
114    fds[0].fd = p1.as_raw_fd();
115    fds[0].events = libc::POLLIN;
116    fds[1].fd = p2.as_raw_fd();
117    fds[1].events = libc::POLLIN;
118    loop {
119        // wait for either pipe to become readable using `poll`
120        cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?;
121
122        if fds[0].revents != 0 && read(&p1, v1)? {
123            p2.set_nonblocking(false)?;
124            return p2.read_to_end(v2).map(drop);
125        }
126        if fds[1].revents != 0 && read(&p2, v2)? {
127            p1.set_nonblocking(false)?;
128            return p1.read_to_end(v1).map(drop);
129        }
130    }
131
132    // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
133    // EAGAIN. If we hit EOF, then this will happen because the underlying
134    // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
135    // this case we flip the other fd back into blocking mode and read
136    // whatever's leftover on that file descriptor.
137    fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> {
138        match fd.read_to_end(dst) {
139            Ok(_) => Ok(true),
140            Err(e) => {
141                if e.raw_os_error() == Some(libc::EWOULDBLOCK)
142                    || e.raw_os_error() == Some(libc::EAGAIN)
143                {
144                    Ok(false)
145                } else {
146                    Err(e)
147                }
148            }
149        }
150    }
151}
152
153impl AsRawFd for AnonPipe {
154    #[inline]
155    fn as_raw_fd(&self) -> RawFd {
156        self.0.as_raw_fd()
157    }
158}
159
160impl AsFd for AnonPipe {
161    fn as_fd(&self) -> BorrowedFd<'_> {
162        self.0.as_fd()
163    }
164}
165
166impl IntoRawFd for AnonPipe {
167    fn into_raw_fd(self) -> RawFd {
168        self.0.into_raw_fd()
169    }
170}
171
172impl FromRawFd for AnonPipe {
173    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
174        Self(FromRawFd::from_raw_fd(raw_fd))
175    }
176}
177
178impl FromInner<FileDesc> for AnonPipe {
179    fn from_inner(fd: FileDesc) -> Self {
180        Self(fd)
181    }
182}