nix/
poll.rs

1//! Wait for events to trigger on specific file descriptors
2use std::os::unix::io::{AsRawFd, RawFd};
3
4use crate::Result;
5use crate::errno::Errno;
6
7/// This is a wrapper around `libc::pollfd`.
8///
9/// It's meant to be used as an argument to the [`poll`](fn.poll.html) and
10/// [`ppoll`](fn.ppoll.html) functions to specify the events of interest
11/// for a specific file descriptor.
12///
13/// After a call to `poll` or `ppoll`, the events that occurred can be
14/// retrieved by calling [`revents()`](#method.revents) on the `PollFd`.
15#[repr(transparent)]
16#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
17pub struct PollFd {
18    pollfd: libc::pollfd,
19}
20
21impl PollFd {
22    /// Creates a new `PollFd` specifying the events of interest
23    /// for a given file descriptor.
24    pub const fn new(fd: RawFd, events: PollFlags) -> PollFd {
25        PollFd {
26            pollfd: libc::pollfd {
27                fd,
28                events: events.bits(),
29                revents: PollFlags::empty().bits(),
30            },
31        }
32    }
33
34    /// Returns the events that occurred in the last call to `poll` or `ppoll`.  Will only return
35    /// `None` if the kernel provides status flags that Nix does not know about.
36    pub fn revents(self) -> Option<PollFlags> {
37        PollFlags::from_bits(self.pollfd.revents)
38    }
39
40    /// The events of interest for this `PollFd`.
41    pub fn events(self) -> PollFlags {
42        PollFlags::from_bits(self.pollfd.events).unwrap()
43    }
44
45    /// Modify the events of interest for this `PollFd`.
46    pub fn set_events(&mut self, events: PollFlags) {
47        self.pollfd.events = events.bits();
48    }
49}
50
51impl AsRawFd for PollFd {
52    fn as_raw_fd(&self) -> RawFd {
53        self.pollfd.fd
54    }
55}
56
57libc_bitflags! {
58    /// These flags define the different events that can be monitored by `poll` and `ppoll`
59    pub struct PollFlags: libc::c_short {
60        /// There is data to read.
61        POLLIN;
62        /// There is some exceptional condition on the file descriptor.
63        ///
64        /// Possibilities include:
65        ///
66        /// *  There is out-of-band data on a TCP socket (see
67        ///    [tcp(7)](https://man7.org/linux/man-pages/man7/tcp.7.html)).
68        /// *  A pseudoterminal master in packet mode has seen a state
69        ///    change on the slave (see
70        ///    [ioctl_tty(2)](https://man7.org/linux/man-pages/man2/ioctl_tty.2.html)).
71        /// *  A cgroup.events file has been modified (see
72        ///    [cgroups(7)](https://man7.org/linux/man-pages/man7/cgroups.7.html)).
73        POLLPRI;
74        /// Writing is now possible, though a write larger that the
75        /// available space in a socket or pipe will still block (unless
76        /// `O_NONBLOCK` is set).
77        POLLOUT;
78        /// Equivalent to [`POLLIN`](constant.POLLIN.html)
79        #[cfg(not(target_os = "redox"))]
80        #[cfg_attr(docsrs, doc(cfg(all())))]
81        POLLRDNORM;
82        #[cfg(not(target_os = "redox"))]
83        #[cfg_attr(docsrs, doc(cfg(all())))]
84        /// Equivalent to [`POLLOUT`](constant.POLLOUT.html)
85        POLLWRNORM;
86        /// Priority band data can be read (generally unused on Linux).
87        #[cfg(not(target_os = "redox"))]
88        #[cfg_attr(docsrs, doc(cfg(all())))]
89        POLLRDBAND;
90        /// Priority data may be written.
91        #[cfg(not(target_os = "redox"))]
92        #[cfg_attr(docsrs, doc(cfg(all())))]
93        POLLWRBAND;
94        /// Error condition (only returned in
95        /// [`PollFd::revents`](struct.PollFd.html#method.revents);
96        /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)).
97        /// This bit is also set for a file descriptor referring to the
98        /// write end of a pipe when the read end has been closed.
99        POLLERR;
100        /// Hang up (only returned in [`PollFd::revents`](struct.PollFd.html#method.revents);
101        /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)).
102        /// Note that when reading from a channel such as a pipe or a stream
103        /// socket, this event merely indicates that the peer closed its
104        /// end of the channel.  Subsequent reads from the channel will
105        /// return 0 (end of file) only after all outstanding data in the
106        /// channel has been consumed.
107        POLLHUP;
108        /// Invalid request: `fd` not open (only returned in
109        /// [`PollFd::revents`](struct.PollFd.html#method.revents);
110        /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)).
111        POLLNVAL;
112    }
113}
114
115/// `poll` waits for one of a set of file descriptors to become ready to perform I/O.
116/// ([`poll(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html))
117///
118/// `fds` contains all [`PollFd`](struct.PollFd.html) to poll.
119/// The function will return as soon as any event occur for any of these `PollFd`s.
120///
121/// The `timeout` argument specifies the number of milliseconds that `poll()`
122/// should block waiting for a file descriptor to become ready.  The call
123/// will block until either:
124///
125/// *  a file descriptor becomes ready;
126/// *  the call is interrupted by a signal handler; or
127/// *  the timeout expires.
128///
129/// Note that the timeout interval will be rounded up to the system clock
130/// granularity, and kernel scheduling delays mean that the blocking
131/// interval may overrun by a small amount.  Specifying a negative value
132/// in timeout means an infinite timeout.  Specifying a timeout of zero
133/// causes `poll()` to return immediately, even if no file descriptors are
134/// ready.
135pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<libc::c_int> {
136    let res = unsafe {
137        libc::poll(fds.as_mut_ptr() as *mut libc::pollfd,
138                   fds.len() as libc::nfds_t,
139                   timeout)
140    };
141
142    Errno::result(res)
143}
144
145feature! {
146#![feature = "signal"]
147/// `ppoll()` allows an application to safely wait until either a file
148/// descriptor becomes ready or until a signal is caught.
149/// ([`poll(2)`](https://man7.org/linux/man-pages/man2/poll.2.html))
150///
151/// `ppoll` behaves like `poll`, but let you specify what signals may interrupt it
152/// with the `sigmask` argument. If you want `ppoll` to block indefinitely,
153/// specify `None` as `timeout` (it is like `timeout = -1` for `poll`).
154/// If `sigmask` is `None`, then no signal mask manipulation is performed,
155/// so in that case `ppoll` differs from `poll` only in the precision of the
156/// timeout argument.
157///
158#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))]
159pub fn ppoll(
160    fds: &mut [PollFd],
161    timeout: Option<crate::sys::time::TimeSpec>,
162    sigmask: Option<crate::sys::signal::SigSet>
163    ) -> Result<libc::c_int>
164{
165    let timeout = timeout.as_ref().map_or(core::ptr::null(), |r| r.as_ref());
166    let sigmask = sigmask.as_ref().map_or(core::ptr::null(), |r| r.as_ref());
167    let res = unsafe {
168        libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd,
169                    fds.len() as libc::nfds_t,
170                    timeout,
171                    sigmask)
172    };
173    Errno::result(res)
174}
175}