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