]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/pipe.rs
Rollup merge of #42496 - Razaekel:feature/integer_max-min, r=BurntSushi
[rust.git] / src / libstd / sys / unix / pipe.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use io;
12 use libc::{self, c_int};
13 use mem;
14 use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
15 use sys::fd::FileDesc;
16 use sys::{cvt, cvt_r};
17
18 ////////////////////////////////////////////////////////////////////////////////
19 // Anonymous pipes
20 ////////////////////////////////////////////////////////////////////////////////
21
22 pub struct AnonPipe(FileDesc);
23
24 pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
25     weak! { fn pipe2(*mut c_int, c_int) -> c_int }
26     static INVALID: AtomicBool = ATOMIC_BOOL_INIT;
27
28     let mut fds = [0; 2];
29
30     // Unfortunately the only known way right now to create atomically set the
31     // CLOEXEC flag is to use the `pipe2` syscall on Linux. This was added in
32     // 2.6.27, however, and because we support 2.6.18 we must detect this
33     // support dynamically.
34     if cfg!(any(target_os = "dragonfly",
35                 target_os = "freebsd",
36                 target_os = "linux",
37                 target_os = "netbsd",
38                 target_os = "openbsd")) &&
39        !INVALID.load(Ordering::SeqCst)
40     {
41
42         if let Some(pipe) = pipe2.get() {
43             // Note that despite calling a glibc function here we may still
44             // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to
45             // emulate on older kernels, so if you happen to be running on
46             // an older kernel you may see `pipe2` as a symbol but still not
47             // see the syscall.
48             match cvt(unsafe { pipe(fds.as_mut_ptr(), libc::O_CLOEXEC) }) {
49                 Ok(_) => {
50                     return Ok((AnonPipe(FileDesc::new(fds[0])),
51                                AnonPipe(FileDesc::new(fds[1]))));
52                 }
53                 Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {
54                     INVALID.store(true, Ordering::SeqCst);
55                 }
56                 Err(e) => return Err(e),
57             }
58         }
59     }
60     cvt(unsafe { libc::pipe(fds.as_mut_ptr()) })?;
61
62     let fd0 = FileDesc::new(fds[0]);
63     let fd1 = FileDesc::new(fds[1]);
64     fd0.set_cloexec()?;
65     fd1.set_cloexec()?;
66     Ok((AnonPipe(fd0), AnonPipe(fd1)))
67 }
68
69 impl AnonPipe {
70     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
71         self.0.read(buf)
72     }
73
74     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
75         self.0.read_to_end(buf)
76     }
77
78     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
79         self.0.write(buf)
80     }
81
82     pub fn fd(&self) -> &FileDesc { &self.0 }
83     pub fn into_fd(self) -> FileDesc { self.0 }
84 }
85
86 pub fn read2(p1: AnonPipe,
87              v1: &mut Vec<u8>,
88              p2: AnonPipe,
89              v2: &mut Vec<u8>) -> io::Result<()> {
90
91     // Set both pipes into nonblocking mode as we're gonna be reading from both
92     // in the `select` loop below, and we wouldn't want one to block the other!
93     let p1 = p1.into_fd();
94     let p2 = p2.into_fd();
95     p1.set_nonblocking(true)?;
96     p2.set_nonblocking(true)?;
97
98     let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
99     fds[0].fd = p1.raw();
100     fds[0].events = libc::POLLIN;
101     fds[1].fd = p2.raw();
102     fds[1].events = libc::POLLIN;
103     loop {
104         // wait for either pipe to become readable using `poll`
105         cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?;
106
107         // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
108         // EAGAIN. If we hit EOF, then this will happen because the underlying
109         // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
110         // this case we flip the other fd back into blocking mode and read
111         // whatever's leftover on that file descriptor.
112         let read = |fd: &FileDesc, dst: &mut Vec<u8>| {
113             match fd.read_to_end(dst) {
114                 Ok(_) => Ok(true),
115                 Err(e) => {
116                     if e.raw_os_error() == Some(libc::EWOULDBLOCK) ||
117                        e.raw_os_error() == Some(libc::EAGAIN) {
118                         Ok(false)
119                     } else {
120                         Err(e)
121                     }
122                 }
123             }
124         };
125         if fds[0].revents != 0 && read(&p1, v1)? {
126             p2.set_nonblocking(false)?;
127             return p2.read_to_end(v2).map(|_| ());
128         }
129         if fds[1].revents != 0 && read(&p2, v2)? {
130             p1.set_nonblocking(false)?;
131             return p1.read_to_end(v1).map(|_| ());
132         }
133     }
134 }