1 use crate::io::{self, IoSlice, IoSliceMut};
3 use crate::sys::fd::FileDesc;
4 use crate::sys::{cvt, cvt_r};
6 ////////////////////////////////////////////////////////////////////////////////
8 ////////////////////////////////////////////////////////////////////////////////
10 pub struct AnonPipe(FileDesc);
12 pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
15 // The only known way right now to create atomically set the CLOEXEC flag is
16 // to use the `pipe2` syscall. This was added to Linux in 2.6.27, glibc 2.9
17 // and musl 0.9.3, and some other targets also have it.
20 target_os = "dragonfly",
21 target_os = "freebsd",
24 target_os = "openbsd",
27 cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) })?;
28 Ok((AnonPipe(FileDesc::new(fds[0])), AnonPipe(FileDesc::new(fds[1]))))
30 cvt(unsafe { libc::pipe(fds.as_mut_ptr()) })?;
32 let fd0 = FileDesc::new(fds[0]);
33 let fd1 = FileDesc::new(fds[1]);
36 Ok((AnonPipe(fd0), AnonPipe(fd1)))
42 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
46 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
47 self.0.read_vectored(bufs)
51 pub fn is_read_vectored(&self) -> bool {
52 self.0.is_read_vectored()
55 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
59 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
60 self.0.write_vectored(bufs)
64 pub fn is_write_vectored(&self) -> bool {
65 self.0.is_write_vectored()
68 pub fn fd(&self) -> &FileDesc {
71 pub fn into_fd(self) -> FileDesc {
76 pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
77 // Set both pipes into nonblocking mode as we're gonna be reading from both
78 // in the `select` loop below, and we wouldn't want one to block the other!
79 let p1 = p1.into_fd();
80 let p2 = p2.into_fd();
81 p1.set_nonblocking(true)?;
82 p2.set_nonblocking(true)?;
84 let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
86 fds[0].events = libc::POLLIN;
88 fds[1].events = libc::POLLIN;
90 // wait for either pipe to become readable using `poll`
91 cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?;
93 if fds[0].revents != 0 && read(&p1, v1)? {
94 p2.set_nonblocking(false)?;
95 return p2.read_to_end(v2).map(drop);
97 if fds[1].revents != 0 && read(&p2, v2)? {
98 p1.set_nonblocking(false)?;
99 return p1.read_to_end(v1).map(drop);
103 // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
104 // EAGAIN. If we hit EOF, then this will happen because the underlying
105 // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
106 // this case we flip the other fd back into blocking mode and read
107 // whatever's leftover on that file descriptor.
108 fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> {
109 match fd.read_to_end(dst) {
112 if e.raw_os_error() == Some(libc::EWOULDBLOCK)
113 || e.raw_os_error() == Some(libc::EAGAIN)