xref: /third_party/rust/crates/nix/test/test_poll.rs (revision 3da5c369)
1use nix::{
2    errno::Errno,
3    poll::{poll, PollFd, PollFlags},
4    unistd::{pipe, write},
5};
6
7macro_rules! loop_while_eintr {
8    ($poll_expr: expr) => {
9        loop {
10            match $poll_expr {
11                Ok(nfds) => break nfds,
12                Err(Errno::EINTR) => (),
13                Err(e) => panic!("{}", e),
14            }
15        }
16    };
17}
18
19#[test]
20fn test_poll() {
21    let (r, w) = pipe().unwrap();
22    let mut fds = [PollFd::new(r, PollFlags::POLLIN)];
23
24    // Poll an idle pipe.  Should timeout
25    let nfds = loop_while_eintr!(poll(&mut fds, 100));
26    assert_eq!(nfds, 0);
27    assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN));
28
29    write(w, b".").unwrap();
30
31    // Poll a readable pipe.  Should return an event.
32    let nfds = poll(&mut fds, 100).unwrap();
33    assert_eq!(nfds, 1);
34    assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN));
35}
36
37// ppoll(2) is the same as poll except for how it handles timeouts and signals.
38// Repeating the test for poll(2) should be sufficient to check that our
39// bindings are correct.
40#[cfg(any(
41    target_os = "android",
42    target_os = "dragonfly",
43    target_os = "freebsd",
44    target_os = "linux"
45))]
46#[test]
47fn test_ppoll() {
48    use nix::poll::ppoll;
49    use nix::sys::signal::SigSet;
50    use nix::sys::time::{TimeSpec, TimeValLike};
51
52    let timeout = TimeSpec::milliseconds(1);
53    let (r, w) = pipe().unwrap();
54    let mut fds = [PollFd::new(r, PollFlags::POLLIN)];
55
56    // Poll an idle pipe.  Should timeout
57    let sigset = SigSet::empty();
58    let nfds = loop_while_eintr!(ppoll(&mut fds, Some(timeout), Some(sigset)));
59    assert_eq!(nfds, 0);
60    assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN));
61
62    write(w, b".").unwrap();
63
64    // Poll a readable pipe.  Should return an event.
65    let nfds = ppoll(&mut fds, Some(timeout), None).unwrap();
66    assert_eq!(nfds, 1);
67    assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN));
68}
69
70#[test]
71fn test_pollfd_fd() {
72    use std::os::unix::io::AsRawFd;
73
74    let pfd = PollFd::new(0x1234, PollFlags::empty());
75    assert_eq!(pfd.as_raw_fd(), 0x1234);
76}
77
78#[test]
79fn test_pollfd_events() {
80    let mut pfd = PollFd::new(-1, PollFlags::POLLIN);
81    assert_eq!(pfd.events(), PollFlags::POLLIN);
82    pfd.set_events(PollFlags::POLLOUT);
83    assert_eq!(pfd.events(), PollFlags::POLLOUT);
84}
85